我想保持程序运行,直到用户输入n退出程序?

时间:2017-10-24 14:48:50

标签: c++

在下面的程序中,我想让代码保持运行,直到用户输入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;
}

2 个答案:

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