#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int num;
int guess;
int diff;
bool isGuessed;
srand(time(0));
num = rand() % 100;
isGuessed = false;
while (!isGuessed)
{
cout << ” Enter an integer greater”
<< ” than or equal to 0 and”
<< ” less than 100 : “;
cin >> guess;
cout << endl;
if (guess == num)
{
cout << ” You guessed the correct ”
<< ” number. ” << endl;
isGuessed = true;
}
else if (guess < num)
cout << ” Your guess is lower than the ”
<< ” number.\n Guess again!”
<< endl;
else
cout << ” Your guess is higher than”
<< ” the number.\n Guess again!”
<< endl;
}
return 0;
}
这是原题,然后老师让我们改 说是加个 diff , (diff 是一个 int variable) 让diff = (Num -guess)的绝对值, 假如diff = 0 然后猜测是对的。
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int num;
int guess;
int diff;
bool isGuessed;
srand(time(0));
num = rand() % 100;
isGuessed = false;
while (!isGuessed)
{
cout << ” Enter an integer greater”
<< ” than or equal to 0 and”
<< ” less than 100 : “;
cin >> guess;
cout << endl;
if (guess == num)
{
cout << ” You guessed the correct ”
<< ” number. ” << endl;
isGuessed = true;
}
else if (guess < num)
cout << ” Your guess is lower than the ”
<< ” number.\n Guess again!”
<< endl;
else
cout << ” Your guess is higher than”
<< ” the number.\n Guess again!”
<< endl;
}
return 0;
}
这是原题,然后老师让我们改 说是加个 diff , (diff 是一个 int variable) 让diff = (Num -guess)的绝对值, 假如diff = 0 然后猜测是对的。
解决方案
160
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int num;
int guess;
int diff;
bool isGuessed;
srand(time(0));
num = rand() % 100;
isGuessed = false;
cout << num;
while (!isGuessed)
{
cout << " Enter an integer greater"
<< " than or equal to 0 and"
<< " less than 100 : ";
cin >> guess;
diff = abs(num - guess);
if (diff == 0)
{
cout << " You guessed the correct "
<< " number. " << endl;
isGuessed = true;
}
else
cout << " Your guess wrong"
<< " the number.\n Guess again!"
<< endl;
}
return 0;
}