I am trying to create my own version of the NIM game. Ok so when I build and run this every thing is smooth until it is computer's turn in which it subtracts 19880494... or something like that every time.. I believe my problem lies within the % operator, but I'm not exactly sure how yet..
#include <iostream>
usingnamespace std;
int main()
{
int total, remainder, x, high, input, replay, com;
x = high;
replay = 1;
while (replay == 1)
{
while (true)
{
cout << "Welcome to the Subtraction Game!" << endl;
cout << "I'm the best at this game." << endl << "OK let's play!" << endl;
cout << "Please enter a total to start from(must be above 2).";
cin >> total;
while (total <= 2)
{
cout << "THE NUMBER MUST BE ABOVE 2." << endl << "Re-enter.";
cin >> total;
}
cout << "Now enter the highest number we can subtract by(Must be above 1).";
cin >> high;
while (high <= 1)
{
cout << "THE NUMBER MUST BE ABOVE 1." << endl << "Re-enter.";
cin >> high;
}
cout << "The total is " << total << "." << endl << "Subtract from it.";
cin >> input;
while (input < 1 || input > high)
{
cout << "Sorry the number you subtract by must be between 1 and " << high << endl << "Please Re-enter." << endl;
cin >> input;
total = total - input;
cout << "You subtracted by " << input << "." << endl << "The new total is " << total;
if (total == 0)
{
cout << "You win!";
break;
}
}
remainder = total % x;
remainder = com;
if (remainder == 0)
{
com = 1;
}
total = total - com;
cout << "I subtracted by " << com << "." << endl << "The new total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl << endl;
break;
}
}
cout << "If you would like to play again enter a 1. If not enter a 2." << endl;
cin >> replay;
while (replay <1 || replay > 2)
{
cout << "You must enter 1 or 2" << endl;
cin >> replay;
}
}
return 0;
}
total = total - input;
cout << "You subtracted by " << input << "." << endl << "The new total is " << total;
if (total == 0)
{
cout << "You win!";
break;
}
1
2
3
4
5
6
7
total = total - input;
cout << "You subtracted by " << input << "." << endl << "The new total is " << total;
if (total == 0)
{
cout << "You win!";
break;
}
should be outside of the loop on line 32-44
1
2
remainder = total % x;
remainder = com;
Edit & Run
what are you trying to do here?
I'm trying to make the number the computer subtracts by equal to the remainder of total and x divided.
remainder = total % x;
com = remainder;
if (remainder == 0)
{
com = 1;
}
I had remainder assigned to com(which had no value).
But I really wanted com assigned the value of remainder!
Thanks everyone!
Thanks Giblit for making me think about it.