这是我第一次在这里发帖,所以如果帖子格式不正确,我很抱歉。我是C ++的新手,正在寻求一些帮助。
我似乎无法弄清楚在大致第18行之后是什么阻止了我的代码。它处理第一个cout和cin,但是继续选择下一个cout?
如果输入密钥,它将运行if / then语句中列出的所有条件并完成。但是,我在这里的目标是让计算机生成一个随机数,然后向我询问输入(Y / N)。鉴于输入,它应该生成另一个随机数或结束。
使用编译器不会产生错误,所以我现在对这个问题有点傻眼。
感谢您的帮助,谢谢。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<iostream.h>
int comp;
using namespace std;
int main ()
{
comp= 1+(rand() % 10);
randomnumber:
string again;
cout <<"The computer chose this random number: "<< comp << endl;
cin >> comp;
cout << "Would you like to run this again? Y/N" << endl;
cin >> again;
if((again == "y")||(again == "Y"))
{
goto randomnumber;
}
else if((again == "n")||(again == "N"))
{
cout << "OK" << endl;
}
else if((again != "y")||(again != "Y")||(again != "n")||(again !="N"))
{
cout << "Please type Y or N" << endl;
}
return 0;
}
答案 0 :(得分:0)
首先让我们看看代码应该满足您要求的内容。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<iostream.h>
//int comp; No need for comp to be a global variable here.
using namespace std;
int main ()
{
int comp;
randomnumber://if you were to use goto, the label should have been here.
comp= 1+(rand() % 10);
//randomnumber: avoid goto statements at all if possible.
//string again; No need for it to be a string.
char again;
cout <<"The computer chose this random number: "<< comp << endl;
//cin >> comp; since you want computer to generate a random no, why ask the user for it?
cout << "Would you like to run this again? Y/N" << endl;
cin >> again;
if((again == "y")||(again == "Y"))
{
goto randomnumber;
}
else if((again == "n")||(again == "N"))
{
cout << "OK" << endl;
}
else if((again != "y")||(again != "Y")||(again != "n")||(again !="N"))
{
cout << "Please type Y or N" << endl;
}
return 0;
}
现在让我们看看如何以更复杂,更简单的方式执行此操作。
#include<iostream.h> //#include<iostream> if No such file error.
#include<time.h> // for seeding rand()
#include<stdlib.h> // for rand
using namespace std;
int main()
{
srand(time(NULL)); //seeding rand()
while(true)
{
int comp=1+(rand() % 10);
cout <<"The computer chose this random number: "<< comp << endl;
cout<<"Would you like to run this again?Y/N"<< endl;
char choice;
cin>>choice;
if ((choice == 'N')|| (choice =='n'))
{
cout<<"OK"<< endl;
break;
}
else
while(choice!='y' && choice!='Y') // forcing user to enter a valid input.
{
cout<<"Please type Y or N" << endl;
cin>>choice;
}
}
return 0;
}
我希望这会有所帮助。