这个程序应该让乌龟和野兔相互比赛并为用户打印比赛。它给了我一个分段错误,我不知道为什么。我甚至用笔和纸仔细阅读了整个代码,看看它是否有用,据我所知它应该有用,但我也是C ++的业余爱好者,所以我不知道。
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
#define RACE_LENGTH 50
void advanceTortoise(int* ptrTortoise)
{
int torNum = rand()%10+1;
if (torNum <= 6)
{
*ptrTortoise = *ptrTortoise + 1;
}else if (torNum = 7) {
*ptrTortoise = *ptrTortoise + 2;
}else if (torNum = 8){
*ptrTortoise = *ptrTortoise + 3;
}else if (torNum > 8){
*ptrTortoise = *ptrTortoise;
if (*ptrTortoise > 50)
{
*ptrTortoise = 50;
}
return;
}
}
void advanceHare(int* ptrHare)
{
int hareNum = rand()%10+1;
if (hareNum = 1)
{
*ptrHare = *ptrHare + 1;
}else if (hareNum > 1 && hareNum <= 4){
*ptrHare = *ptrHare + 2;
}else if (hareNum > 4 && hareNum <= 7){
*ptrHare = *ptrHare + 3;
}else if (hareNum = 8){
*ptrHare = *ptrHare - 2;
if (*ptrHare < 1)
{
*ptrHare = 1;
}
}else if (hareNum > 8){
*ptrHare = *ptrHare - 3;
if (*ptrHare < 1)
{
*ptrHare = 1;
}
if (*ptrHare > 50)
{
*ptrHare = 50;
}
return;
}
}
void printPosition(int* ptrTortoise, int* ptrHare)
{
if (*ptrTortoise = *ptrHare)
{
*ptrTortoise = *ptrTortoise - 1;
}
if (*ptrTortoise > *ptrHare)
{
std::cout << std::setw(*ptrHare - 1) << "H" << std::setw(*ptrTortoise - *ptrHare) << "T" << std::setw(51 - *ptrTortoise) << "|" <<std::endl;
}
if (*ptrHare > *ptrTortoise)
{
std::cout << std::setw(*ptrTortoise - 1) << "H" << std::setw(*ptrHare - *ptrTortoise) << "T" << std::setw(51 - *ptrHare) << "|" <<std::endl;
}
}
int main()
{
srand(time(NULL));
int* ptrTortoise;
int* ptrHare;
*ptrTortoise = 1;
*ptrHare = 1;
while(*ptrTortoise < 50 && *ptrHare < 50)
{
advanceHare(ptrHare);
advanceTortoise(ptrTortoise);
printPosition(ptrTortoise, ptrHare);
}
if (*ptrHare = 50)
{
std::cout<<"The Hare has won"<<std::endl;
}else{
std::cout<<"The Tortoise has won"<<std::endl;
}
}
答案 0 :(得分:1)
这里有一些事情。
==
),而不是赋值(=
)运算符。因此,你应该改变:
int* ptrTortoise;
int* ptrHare;
要:
int* ptrTortoise = new int{ 1 };
int* ptrHare = new int{ 1 }; // Don't forget to get rid of the two lines after this
或者更好:
int tortoise = 1;
int hare = 1;
如果您使用了最后一个选项,则更改所有功能签名以接受引用(例如将int* ptrTortoise
更改为int& ptrTortoise
)。接下来,删除你必须在代码中的任何地方取消引用指针的所有实例,而不是直接分配给变量,这更有意义并且输入更少(引用不是很好吗?)。
经验法则:除非绝对必须,否则不要使用指针。