我没有得到一个数字作为输出,而是一个表情符号

I am not getting a number as output but instead a emoji

本文关键字:一个 符号 输出 数字      更新时间:2023-10-16

在此处输入图像描述我编写了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;
}

输出应为整数。但输出只是一颗钻石。

将变量结果声明为具有 int 类型

int result = 0;

或者也许最好将其声明为

long long int result = 0;

并像使用它一样使用

result = static_cast<long long int>( num1 ) * num2;

在您的程序中,它具有类型std::string

string result;

您正在为字符串分配一个整数值,所以我认为它是将该整数值转换为字符值并提供该表情符号。我的情况和你的一样,我 正在为字符串分配整数值。但是我随后将该整数值声明为字符值,然后它工作正常。

此外,最好的方法是使用 to_string(( 函数将整数值更改为字符值。