#include <iostream>
using namespace std;
int main() {
char choice;
int solution, num1, num2;
cout << "Menu";
cout << "\n========";
cout << "\n+) Add";
cout << "\n-) subtract";
cout << "\n*) Multiplication";
cout << "\n/) Division";
cout << "\nx) Exit";
cout << endl;
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice) {
case '+':
cout << "\nEnter the operands: ";
cin >> num1, num2;
solution = num1 + num2;
cout << num1 << '+' << num2 << '=' << solution;
break;
case '-':
cout << "\nEnter the operands: ";
cin >> num1, num2;
solution = num1 + num2;
cout << num1 << '-' << num2 << '=' << solution;
break;
case '*':
cout << "\nEnter the operands: ";
cin >> num1, num2;
solution = num1 * num2;
cout << num1 << '*' << num2 << '=' << solution;
break;
case '/':
cout << "\nEnter the operands: ";
cin >> num1, num2;
solution = num1 / num2;
cout << num1 << '/' << (double)num2 << '=' << solution;
break;
case 'x':
case 'X':
cout << "\nExiting....";
return 0;
break;
default:
cout << "\nInvalid choice";
}
return 0;
}
所以我正在编写一个允许用户输入操作的程序。它几乎是一个计算器!我必须使用 switch 语句。我觉得我已经很接近了,但现在我碰壁了。在用户输入一个操作后,程序运行并说它输入操作数,然后它应该用输入的数字进行操作并显示它们。在用户输入程序刚刚崩溃的 2 个操作数后,出现了某种类型的问题。关于它可能是什么有什么建议吗?
最佳答案
cin >> num1, num2;
此语法不符合您的要求。要链接,请使用
cin >> num1 >> num2;
如果编译时出现警告,编译器会通知你
int a{}, b{};
std::cin >> a, b;
给出错误:
warning: right operand of comma operator has no effect [-Wunused-value]
std::cin >> a, b;
整个语句被解析为
((std::cin >> a), b);
由两个逗号分隔的表达式组成。 b
在这种情况下没有任何效果。如果在上面的 std::cin
行之后打印变量,对于 b
0
关于c++ - cin >> num1, num2 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288245/