C++基本计算器
C++ Basic Calculator
我是一般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
的结果应该是什么?
在这种情况下,您可以使用int
s:
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 == '%')
.
相关文章:
- 使用 BMI 计算器对C++中的数字进行四舍五入的问题
- 我在c ++矩阵计算器程序中找不到错误
- C++计算器,不能单独除以 0
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- Arduino 基础 2 计算器无法C++工作
- 需要有关我的平均计算器代码的建议
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- C++计算器运算符
- 使用WIN32 API的击球平均计算器
- RPN计算器c++错误处理和多个运算符
- C++查找用于构建单行计算器
- 如何修复这个基本计算器
- 用于加法和减法的十六进制计算器
- 桌面计算器出现问题.C++程序设计语言
- 如何对堆栈中的所有项目求和?Postfix计算器
- RPN计算器使用头文件进行计算操作和堆栈;用于堆栈的矢量
- 如何在我的基本计算器中循环遍历数组
- 如果 GPA 计算器的语句问题
- 我的C++计算器似乎出了什么问题?