0 c++
#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;
}
Run Code Online (Sandbox Code Playgroud)
所以我正在编写一个允许用户输入操作的程序.它几乎是一个计算器!我必须使用switch语句.我觉得我很亲密,但现在我已经打了一堵砖墙.在用户启动操作之后,程序运行并说它进入操作数,然后它应该用输入的数字进行操作并显示它们.在用户输入程序崩溃的2个操作数之后,这是一些问题.有什么建议吗?
cin >> num1, num2;
Run Code Online (Sandbox Code Playgroud)
此语法不适合您的需要.链,使用
cin >> num1 >> num2;
Run Code Online (Sandbox Code Playgroud)
如果您使用警告进行编译,编译器将通知您
int a{}, b{};
std::cin >> a, b;
Run Code Online (Sandbox Code Playgroud)
给出错误:
warning: right operand of comma operator has no effect [-Wunused-value]
std::cin >> a, b;
Run Code Online (Sandbox Code Playgroud)
整个语句被解析为
((std::cin >> a), b);
Run Code Online (Sandbox Code Playgroud)
其中包含两个以逗号分隔的表达式.该b在这种情况下,没有任何效果.如果您在打印后的变量std::cin线之上,你总是会得到0的b