C++基本计算器

C++ Basic Calculator

本文关键字:计算器 C++      更新时间:2023-10-16

我是一般C++和编程的新手。我被分配为我的C++课制作一个计算器,这就是我迄今为止所拥有的。

#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op = '+')
{
cout << "Result:" << x + y << endl;
}
else if (op = '-') {
cout << "Result:" << x - y << endl;
}
else if (op = '*') {
cout << "Result:" << x*y << endl;
}
else if (op = '/') {
cout << "Result:" << x / y << endl;
}
else if (op = '%') {
cout << "Result:" << x % y << endl; // <--- line 23
}
else {
return 0;
}
}

第 23 行的 x 和 y 变量都有错误,说表达式必须具有整数或无作用域枚举类型,我不明白为什么。

仅为整数值定义%运算。您不能将其应用于双打。此外,您还有一个典型的新手错误:在C++operator =中,赋值运算符a = b表示获取 b 值并将其放入 a 中。但是operator ==是比较运算符,a == b的意思是如果a同样b返回true。如果要比较值,请使用==,而不是=

浮点除法没有余数。2.5 % 1.2的结果应该是什么?

在这种情况下,您可以使用ints:

else if (op == '%') {
cout << "Result:" << (int)x % (int)y << endl;
}

但请注意,当用户键入2.5 % 1.2时,将显示2 % 1的结果。

PS:另请注意,您在应该==(比较)的条件中=(分配)。

你用%表示双精度,它只用于整数。 如果要对双精度使用相同的功能。你可以使用 fmod()

double z = fmod(x,y);

您应该将代码修改为以下内容

#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op == '+')
{
cout << "Result:" << x + y << endl;
}
else if (op == '-') {
cout << "Result:" << x - y << endl;
}
else if (op == '*') {
cout << "Result:" << x*y << endl;
}
else if (op == '/') {
cout << "Result:" << x / y << endl;
}
else if (op == '%') {
cout << "Result:" << fmode(x,y) << endl;
}
else{
return 0;
}
}

余数运算符%不适用于double类型的操作数(例如,cppreference.com/Multiplicative 运算符):

对于内置算子%,lhs 和 rhs 都必须具有积分或 无作用域枚举类型

你可以改写static_cast<int>(x)%static_cast<int>(y)

此外,请注意,=是赋值运算符;为了进行比较(如if (op = '%')的情况),请使用相等运算符==,即if (op == '%').