C++ 如何使用从cin读取的变量计算表达式
我正在试着做一个基本的计算器,但是我没有得到我期望的答案。这是我的代码:C++ 如何使用从cin读取的变量计算表达式,c++,C++,我正在试着做一个基本的计算器,但是我没有得到我期望的答案。这是我的代码: char x; int y; int z; cout << "Welcome to the Calculator!\n"; cout << "What operation would you like to use?\n"; cin >> x; cout << "What will be the first integer?\n"; cin >> y; co
char x;
int y;
int z;
cout << "Welcome to the Calculator!\n";
cout << "What operation would you like to use?\n";
cin >> x;
cout << "What will be the first integer?\n";
cin >> y;
cout << "What will be the second?\n";
cin >> z;
cout << "Computing...\n";
cout << y << x << z;
同样,如果我输入+
、8
和4
,我会得到:
8+4
我希望输出分别为
3
和12
。您需要测试用户输入的字符,并使用它来确定应用哪个操作。因此,如果输入例如“-”,则执行操作y-z
我认为解决此问题的最简单方法是从小处着手。制作一个具有单一功能的计算器:将数字相加的计算器。突然,您的代码是:
cout << "What will be the first integer?\n";
cin >> y;
cout << "What will be the second?\n";
cin >> z;
auto result = y + z;
std::cout << result << "\n";
另外,您还需要添加对输入的无效操作的处理。您是否正在尝试执行
9-6
并输出结果(即3
)?是的,但只是遇到麻烦我不知道问题是什么。请仔细解释,你不能在C++中“执行”变量,你需要自己编写代码(例如:使用一个代码>开关(x)< /Cord>检查用户输入了什么操作符)
cout << "What will be the first integer?\n";
cin >> y;
cout << "What will be the second?\n";
cin >> z;
auto result = y + z;
std::cout << result << "\n";
std::cout << "Would you like to add or subtract numbers? ";
char operation;
std::cin >> operation;
int result;
if (operation == '+')
{
result = y + z;
}
else
{
result = y - z;
}
int result;
switch (operation)
{
case '+': result = y + z; break;
case '-': result = y - z; break;
case '*':
case 'x':
result = y * z; break;
}