如何给这个简单的 c++ 程序一个适当的循环
How to give this simple c++ program a proper loop
我是一个编程初学者,我正在做一个我在互联网上找到的练习:
制作一个计算器,它接受 3 个输入并加、减、乘或除两个数字。第一个和第三个输入是整数。第二个是炭。
- 使用 switch 语句根据用户输入确定要执行的操作。
- 至少使用一个函数。
- 让程序再次询问输入是否无效。
- 使程序在完成后循环,在完全退出之前允许多次使用。
这是我的代码:
#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');
}
相关文章:
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- C++-字符串是否包含一个带有简单循环的单词
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 使用一个循环与两个循环
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- 使用一个 for 循环如何迭代和测试迭代器值?
- 我正在尝试创建一个菜单,但我的代码一直在循环
- 转到基于范围的 for 循环中的下一个迭代器
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 如何循环 n 次,在 xml 文件中每个循环一个级别
- 初始化时 num 的哪个值会给这个嵌套循环一个"true"输出?
- 两次相同的 for 循环:一个编译,另一个不编译
- 如何在C 中循环一个语句
- 循环一个级数
- 如何在c++中循环一个函数
- 循环一个精灵以显示不止一次
- C++循环一个菜单,直到选择了所有选项
- QT:如何每秒循环一个方法?C++
- 循环一个mpl::map