在特定条件下的循环和简单计算器的结尾
Loop and end of simple calculator on a specific condition
我是C 的新手,我一直在弄清楚这一点。我完成了这个简单的计算器,但我需要在其中添加两个特定条件。
*首先,如果第一个输入为数字,我需要在完成后循环。
*第二,如果第一个输入是非数字,我需要程序才能结束。
我将如何解决这个问题?谢谢。
#include <iostream>
using namespace std;
int main()
{
float num_1,num_2;
char operator_1;
cout << "Enter a number, an operator, and another number: " << endl;
cin >> num_1;
cin >> operator_1;
cin >> num_2;
cout << num_1 << " ";
cout << operator_1 << " ";
cout << num_2 << " = ";
switch (operator_1)
{
case '+':
cout << num_1 + num_2;
break;
case '-':
cout << num_1 - num_2;
break;
case '*':
cout << num_1 * num_2;
break;
case '/':
cout << num_1 / num_2;
break;
}
return 0;
}
您想要类似的东西:
int main()
{
float num_1, num_2;
char operator_1;
while (true) {
cout << "Enter a number, an operator, and another number: " << endl;
if (!(cin >> num_1)) {
cout << "Error" << endl;
return 0;
}
cin >> operator_1;
cin >> num_2;
cout << num_1 << " ";
cout << operator_1 << " ";
cout << num_2 << " = ";
switch (operator_1)
{
case '+':
cout << num_1 + num_2 << endl;
break;
case '-':
cout << num_1 - num_2 << endl;
break;
case '*':
cout << num_1 * num_2 << endl;
break;
case '/':
cout << num_1 / num_2 << endl;
break;
}
}
return 0;
}
请注意如何捕获num_1
中的错误以及while
循环中的所有内容。该程序仅在第一个输入不正确的情况下结束。
相关文章:
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 创建一个简单的计算器,添加时遇到问题
- 简单计算器的难以理解功能(Stroustrop 编程原理书)
- C++:我的简单计算器程序无法打印出来。我也认为我的变量命名不正确
- DEV简单的C GPA计算器问题
- 在特定条件下的循环和简单计算器的结尾
- C++简单的计算器(没有如果,开关,案例及其种类)
- 简单平均计算器的问题
- 使用命令行和C++的简单计算器
- C++简单的计算器
- 简单的计算器程序出了什么问题
- 简单计算器C++
- 简单的计算器
- C++ - 简单的形状面积计算器返回错误的计算
- 简单计算器尝试重新学习C++.左值错误
- 简单的计算器应该需要2秒钟来修复它的10行
- 简单的计算器问题(不输出答案)
- 模板化一个简单的Boost Proto C++表达式计算器
- 我的简单计算器没有开关盒的新想法
- 简单计算器帮助(c++)