在下面的程序中,我想让代码保持运行,直到用户输入n
来停止程序。任何人都可以帮我这么做吗?
#include<iostream>
using namespace std;
int main()
{
int i,num,f;
f=1;
i=1;
cout<<"Enter a value to get its factorial : ";
cin>>num;
while(i<=num)
{
f=f*i;
i++;
}
cout<<"Factorial of "<<num<<" is "<<f<<endl;
}
答案 0 :(得分:5)
您可以使用do-while循环。
#include<iostream>
using namespace std;
int main()
{
char ch;
do{
int i,num,f;
f=1;
i=1;
cout<<"Enter a value to get its factorial : ";
cin>>num;
while(i<=num)
{
f=f*i;
i++;
}
cout<<"Factorial of "<<num<<" is "<<f<<endl;
cout<<"Wanna continue?";
cin>>ch;
}while(ch != 'n');
}
答案 1 :(得分:0)
您可以将代码包装成循环并检索std::string
输入以检查
#include<iostream>
#include <string>
using namespace std;
int main()
{
int i,num,f;
string input;
while(1) {
f=1;
i=1;
cout<<"Enter a value to get its factorial or 'n' to exit: ";
if(cin >> input && input != "n") {
num = stoi(input);
while(i<=num)
{
f=f*i;
i++;
}
cout<<"Factorial of "<<num<<" is "<<f<<endl;
}
else {
break;
}
}
}