enter image description here我编写了C ++程序,该程序要求用户提供两个数字和一个运算符,并根据输入给出输出。我认为一切正确,但输出不是所需的输出。
#include <iostream>
using namespace std;
int main()
{
int num1;
string op;
int num2;
string result;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter a operator: ";
cin >> op;
cout << "Enter another number: ";
cin >> num2;
if (op == "+"){ //if user types '+' the result is num1 + num2
result = num1 + num2;
//cout << result;
}else if (op == "-"){ //if user types '-' the result is num1 - num2
result = num1 - num2;
// cout << result;
}else if (op == "*"){ //if user types '*' the result is num1 * num2
result = num1 * num2;
//cout << result;
}else if (op == "/"){ //if user types '/' the result is num1 / num2
result = num1 / num2;
//cout << result;
}else{
cout << "Invalid operator...";
}
cout << result;
return 0;
}
输出应该是整数。但是输出只是一个菱形。
答案 0 :(得分:4)
将变量结果声明为int类型
int result = 0;
或者将其声明为
long long int result = 0;
并像使用它
result = static_cast<long long int>( num1 ) * num2;
程序中的类型为std::string
string result;