C++无效操作数错误

C++ Invalid Operands Error

本文关键字:错误 操作数 无效 C++      更新时间:2023-10-16

我正在编写一个程序,计算一行的斜率并将其显示出来。我在几乎所有这些行上都得到了以下错误:"错误:类型为双(int,int,int)的无效操作数"answers"int"到二进制"运算符*"。我不知道它为什么不让我把一个二重和一个int相乘。我们很感激你的帮助。

 double figure_slope(int x1, int y1, int x2, int y2)                                                                           
}
 (y1-y2)/(x1-x2);
}
void determine_line(int x1, int y1, int x2, int y2)
{
if (figure_slope == 1 && y1 - figure_slope*x1 == 0)
cout << "Equation: x = " << x1 << endl;
else
if (figure_slope == 0 && y1 - figure_slope*x1 == 0)
  cout << "Equation: y = 0" << endl;
else
  if (figure_slope == 0)
    cout << "Equation: y = " << y1 - figure_slope*x1) << endl;
  else
    if (y1 - figure_slope*x1 == 0)
      cout << "Equation: y = " << figure_slope << "x" << endl;
    else
      if (y1 - figure_slope*x1 < 0)
        cout << "Equation: y = " << figure_slope << "x - " << -(y1 - figure_slope*x1) <<   endl;
      else
        cout << "Equation: y = " << figure_slope << "x + " << y1 - figure_slope*x1 << endl;
}

figure_slope在使用时只是一个函数指针。您定义它接受参数,但没有传入任何参数。您需要像if (figure_slope(x1, y1, x2, y2) == 0 && ....一样调用它。

此外,figure_slope()返回一个double,但您正在与int进行比较。这可能不会像你预期的那样奏效。

double figure_slope(int x1, int y1, int x2, int y2)                                                                           
}
 (y1-y2)/(x1-x2);
}

第2行的大括号不正确。它还需要"回归"。除此之外,如果您想要一个浮点结果,则需要将每一侧强制转换为double类型。

请尝试以下操作:

double figure_slope(int x1, int y1, int x2, int y2){
    return static_cast<double>(y1-y2)/static_cast<double>(x1-x2);
}

除此之外,当您调用函数时,还需要为其提供参数。由于您将在每个地方使用相同的参数调用它,因此只需调用一次并将结果分配给一个值即可。尝试以下操作:

void determine_line(int x1, int y1, int x2, int y2){
    double figureSlope = figure_slope(x1, y1, x2, y2);
    if(figureSlope == 1 && y1 - figureSlope*x1 == 0)
        cout << "Equation: x = " << x1 << endl;
    else if(figureSlope == 0 && y1 - figureSlope*x1 == 0)
        cout << "Equation: y = 0" << endl;
    else if(figureSlope == 0)
        cout << "Equation: y = " << y1 - figureSlope*x1) << endl;
    else if(y1 - figureSlope*x1 == 0)
        cout << "Equation: y = " << figureSlope << "x" << endl;
    else if(y1 - figureSlope*x1 < 0)
        cout << "Equation: y = " << figureSlope << "x - " << -(y1 - figureSlope*x1) << endl;
    else
        cout << "Equation: y = " << figureSlope << "x + " << y1 - figureSlope*x1 << endl;
}

请注意,在每种情况下,您都在将int与double进行比较。您可能需要更多的static_cast调用,以确保获得预期的结果。

相关文章: