如何解决错误:类型为'double'和'double'的二进制类型的'operator%'无效操作数
我一直在做一个身高预测计算器,但是编译时遇到错误
#include <iostream>
#include <string>
using namespace std;
int main() {
int i = 0;
do {
double mom;
double dad;
string boygirl;
double fullboy = (mom * 13 / 12 + dad) / 2;
double fullgirl = (dad + 12 / 13 + mom) / 2;
double twsub = 12;
double twsub2 = 12;
cout << " \n\nWELCOME TO THE C++ HEIGHT PREDICTION PROGRAM";
cout << "\n\n INPUT GENDER TO BEGIN boy/girl: ";
cin >> boygirl;
cout << "How tall is your mother in inches: ";
cin >> mom;
cout << "How tall is your father in inches: ";
cin >> dad;
if (boygirl == "boy") {
cout << fullboy % twsub2 << "ft"
<< "is your estimated height";
}
else if (boygirl == "girl") {
cout << fullgirl % twsub << "ft"
<< " is your estimated height";
}
++i;
} while (i < 10);
}
错误是
error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%
通过以下几行代码会发生这种情况:
if (boygirl == "boy") {
cout << fullboy % twsub2 << "ft" << "is your estimated height";
}
和
else if (boygirl == "girl") {
cout << fullgirl % twsub << "ft" << " is your estimated height";
}
我想知道是否有人可以帮助我修复代码中的错误
谢谢
解决方法
在C ++中,只能在诸如%
之类的整数类型上使用模运算符int
。对于double
之类的浮点类型,您可以使用标准库提供的函数std::fmod()
:
std::cout << std::fmod( fullboy,twsub2 ) << "ft is your estimated height";
请注意,此代码中还存在整数除法的问题:
double fullgirl = (dad + 12 / 13 + mom) / 2;
应该是这样的:
double fullgirl = (dad + 12.0 / 13.0 + mom) / 2.0;
尽管在这一行中您没有这样的问题:
double fullboy = (mom * 13 / 12 + dad) / 2;
最好在每个地方都这样做,这是防止出错的好习惯。详细信息可以在这里Why does this calculation (division) return a wrong result?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。