0

我一直在制作高度预测计算器,但编译时出现错误

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

我想知道是否有人可以帮我解决我的代码中的这个错误

谢谢

4

1 回答 1

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;

最好在任何地方都这样做,作为防止错误的好习惯。详情可以看这里为什么这个计算(除法)会返回错误的结果?

于 2020-11-01T22:34:55.087 回答