如何创建无需重新运行即可获得新结果的程序?

How can I create a program that doesn't need to rerun to get new results?

本文关键字:结果 新结果 程序 可获得 重新运行 何创建 创建      更新时间:2023-10-16

我刚刚编写了基于用户输入计算乘法表的代码。问题是,在我打印结果后,程序关闭,我需要重新启动它以获得不同的输入和结果。

我想要得到结果,并按下一个键从用户那里得到一个新的值:我不想要不断地关闭和打开程序。我该怎么做呢?
这是我的代码:

#include <iostream>
using namespace std;
int main() 
{
    int a, range;
    cout << "Introduce value: ";
    cin >> a;
    printf("n");
    cout << "Introduce range: ";
    cin >> range;
    printf("n");
    for (int i = 1; i <= range; ++i) 
    {
        cout << a << " * " << i << " = " << a*i << endl;
    }
    printf("n");
    system("pause");
}

添加while(1)

#include <iostream>
using namespace std;
int main() 
{
    while(1){
    int a, range;
    cout << "Introduce value: ";
    cin >> a;
    printf("n");
    cout << "Introduce range: ";
    cin >> range;
    printf("n");
    for (int i = 1; i <= range; ++i) 
    {
        cout << a << " * " << i << " = " << a*i << endl;
    }
    printf("n");
    system("pause");
    }
}

因为while语句中的条件总是为真,所以这里的代码将永远循环!

如果你想按一个键来决定是否继续使用另一个值,请使用do while循环。

int main(void){
char c;
do{
   //......your code

   cout<<"Do you want to continue?"; // press 'y' if yes
   cin>>c;
}while(c=='y');
return 0;
}

按"y"继续或按其他任何停止。有了这段代码,你不需要system("Pause")在结束