C++遇到难题不会了,基础题,求指导

C语言 码拜 8年前 (2016-05-28) 841次浏览
#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 然后猜测是对的。
解决方案

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;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++遇到难题不会了,基础题,求指导
喜欢 (0)
[1034331897@qq.com]
分享 (0)