错误:类型为'double'和'double'的二进制类型的'operator%'无效操作数

时间:2020-11-01 22:27:14

标签: c++ debugging double height calculator

我一直在做一个身高预测计算器,但是编译时遇到错误

#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";
}

我想知道是否有人可以帮助我修复代码中的错误

谢谢

1 个答案:

答案 0 :(得分:1)

在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?

相关问题