#include
#include
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1;
int a = 0;
cout << "请输入您所认为的数字" << endl;
cin >> a;
int c = 0;
while (c <= 5)
{
c = c + 1;
if(c<=5){
if (a > num)
{
cout << "错误,数字过大" << endl;
}
else if (a < num)
{
cout << "错误,数字偏小" << endl;
}
else
{
cout << "正确" << endl;
break;
}
}
}
system("pause");
return 0;
}
修改如下,供参考:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1;
int a = 0;
cout << "请输入您所认为的数字" << endl;
cin >> a;
int c = 0;
while (c != 5-1)
{
//if (c <= 5) {
if (a > num)
{
cout << "错误,数字过大" << endl;
}
else if (a < num)
{
cout << "错误,数字偏小" << endl;
}
else
{
cout << "正确" << endl;
break;
}
c = c + 1;
cin >> a;
//}
}
system("pause");
return 0;
}
你已经在while中写了判断了。不必在while循环体中再写一次if
while永远满足if的条件,如果不满足,不会走while
c初始值为0,while(c<=5),这样实际会循环6次,把判断条件改为c<5,无论是while还是里面的if。
int main()
{
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1;
int a = 0;
cout << "请输入您所认为的数字" << endl;
cin >> a;
int c = 0;
while (c < 5)
{
c = c + 1;
if (a > num)
{
cout << "错误,数字过大,请重新输入" << endl;
cin>>a;
continue;
}
else if (a < num)
{
cout << "错误,数字偏小,请重新输入" << endl;
cin>>a;
continue;
}
else
{
cout << "正确" << endl;
break;
}
}
}
system("pause");
return 0;
}
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1;
int a = 0;
cout << "请输入您所认为的数字" << endl;
//cin >> a;
int c = 0;
while (c != 5)
{
cin >> a;
if (a > num)
{
cout << "错误,数字过大" << endl;
}
else if (a < num)
{
cout << "错误,数字偏小" << endl;
}
else
{
cout << "正确" << endl;
break;
}
c = c + 1;
}
system("pause");
return 0;
}