This program is supposed to have a tortoise and hare race each other and print the race out for the user. It is giving me a segmentation fault and I do not know why. I even went through the whole code with a pen and paper to see if it worked and to my knowledge it should work but I am also an amateur to C++ so I do not know.
#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;
}
}
Aucun commentaire:
Enregistrer un commentaire