【发布时间】:2018-02-09 21:50:41
【问题描述】:
这个程序应该让龟兔赛跑并为用户打印比赛。它给了我一个分段错误,我不知道为什么。我什至用笔和纸检查了整个代码,看看它是否有效,据我所知它应该有效,但我也是 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;
}
}
【问题讨论】:
-
您还需要了解使用
=进行赋值和使用==比较相等性之间的区别。 -
至于你的问题,你定义了几个指针变量,但你没有让它们真正point到任何地方。了解如何使用 address-of 运算符
&。那么main函数中不需要任何指针。或者更好的是,如何return您的函数中的值,并且您在这里根本不需要任何指针。 Get a couple of good beginners books阅读! -
你为什么在这里使用指针?您永远不会在 main 中为它们分配任何内存。
-
您不能只分配给这样的指针。首先,您必须分配内存(在这里 new 将是一个好主意,或者更好的是,摆脱指针)。如果要修改参数,请使用引用。
-
您还需要为您使用的任何编译器打开警告。 gcc、clang 和 Visual Studio 都会抱怨代码行不正确。