如何在C++中使用循环

How to use looping in C++

本文关键字:循环 C++      更新时间:2023-10-16

我是C++新手,我正在制作一个程序来生成乘法表。这是他的代码。

#include <iostream>
using namespace std;
int main()
{
  int num;
    cout << "Enter a number to find Multiplication Table   ";
       cin >>num;
            for(int a=1;a<=10;a++)
                     {
                        cout<<num<<" x "<<a<<" = "<<num*a<<endl;
                     }
       cout << "Press ENTER to continue...n";
       cin.get();
       getchar();
       return 0;
}

我希望在显示一个数字的乘法表后,用户应该可以选择输入另一个数字或退出。比如按"n"输入新号码或按"e"退出

这可能是你想要的。(这是主函数的实现)

int num;
char command;
bool exit=false;
while(!exit)
{
    cout << "Enter a number to find Multiplication Table   ";
    cin >>num;
    for(int a=1;a<=10;a++)
    {
         cout<<num<<" x "<<a<<" = "<<num*a<<endl;
    }
    cout << "Press n to continue or e to exitn";
    cin >> command;
    while(command != 'n' && command != 'e')
    {
        cout << "Just press n to continue or e to exit!n";
        cin >> command;
    }
    if (command == 'e')
    {
        exit=true;
    }else
    {
        exit=false;
    }
}
return 0;
#include <iostream>
using namespace std;
int main()
{
  int num;
  char ch;
  do{
       cout << "Enter a number to find Multiplication Table";
       cin >> num;    
       for(int a=1;a<=10;a++)
       {
           cout<<num<<" x "<<a<<" = "<<num*a<<endl;
       }
       cout << "Press "n" to enter a new number or "e" to exitn";
  }while(cin>>ch && ch=='n');
  return 0;
}