如何给这个简单的 c++ 程序一个适当的循环

How to give this simple c++ program a proper loop

本文关键字:循环 一个 c++ 简单 程序      更新时间:2023-10-16

我是一个编程初学者,我正在做一个我在互联网上找到的练习:

制作一个计算器,它接受 3 个输入并加、减、乘或除两个数字。第一个和第三个输入是整数。第二个是炭。

  1. 使用 switch 语句根据用户输入确定要执行的操作。
  2. 至少使用一个函数。
  3. 让程序再次询问输入是否无效。
  4. 使程序在完成后循环,在完全退出之前允许多次使用。

这是我的代码:

#include <iostream>
using namespace std;
int main()
{
int number1 , number2;
char operator_;
cout << "enter first number:" << endl;
cin >> number1;
cout << "enter operator:";
cin >> operator_;
cout << "enter second number:" << endl;
cin >> number2;
switch (operator_)
{
case '+':
    cout << " the sum is " << number1 + number2;
    break;
case '-':
    cout << "the difference is " <<number1 - number2;
    break;
case '*':
    cout <<  "the product is " << number1 * number2;
    break;
case '/':
    cout << "the quotient is " << number1 / number2;
    break;
default:
    cout << "Invalid Operation";
}
return 0;
}

如何完成任务 3 和 4?我在循环时学习,但我不知道这将如何帮助我的程序。

只需在

main 函数中的所有代码之外添加一个无限循环,最后询问用户是否要继续。如果没有,那么break出圈。

如果您愿意,您可以一次完成这两项操作。

首先重命名你的主函数,称它为类似do_calculation。

现在编写一个新的主函数。这将包含一个循环,询问用户是否要重试,它将调用您刚刚创建的do_calculation函数。像这样的东西

int main()
{
    char try_again;
    do
    {
        do_calculation();
        cout << "Do you want to try again (answer Y or N) ";
        cin >> try_again;
    }
    while (try_again == 'y' || try_again == 'Y');
}