编写二次公式程序时的编译错误

时间:2012-02-08 03:10:52

标签: c++ math

无法使此代码编译并正常工作

实施档案:

#include <cmath>
#include "quadEquation.h"
using namespace std;

QuadEquation::QuadEquation()
{
  int a,b,c;
}

QuadEquation::QuadEquation(int first, int second, int third)
{
  a = first;
  b = second;
  c = third;
}

int QuadEquation::getA()
{
  return a;
}
int QuadEquation::getB()
{
  return b;
}
int QuadEquation::getC()
{
  return c;
}
int QuadEquation::getDiscriminant()
{
  return b * b - 4 * a * c;
}
int QuadEquation::getRoot1()
{
  discrim = getDiscrimant();
  return -b + sqrt(discrim) / (2 * a);
}
int QuadEquation::getRoot2()
{
  discrim = getDiscriminant();
  return -b - sqrt(discrim) / (2 * a);
}

标题文件:

#ifndef QUADEQUATION_H
#define QUADEQUATION_H

class QuadEquation
{
 private:
  int a, b, c;

 public:
  QuadEquation(int, int, int);
  int getA();
  int getB();
  int getC();
  int getDiscriminant();
  int getRoot1();
  int getRoot2();
};

#endif

#include <iostream>
#include "quadEquation.h"
using namespace std;

int main()
{
  QuadEquation quad1(1,0,9);
  cout << "The first root  of the first quadratic equation is: " << quad1.getRoot1() << endl;

  return 0;
}

我得到的一些错误

quadEquation.cpp:5: error: prototype for ‘QuadEquation::QuadEquation()’ does not match any in class `QuadEquation`
quadEquation.h:5: error: candidates are: `QuadEquation::QuadEquation(const QuadEquation&)`
quadEquation.h:10: error:                `QuadEquation::QuadEquation(int, int, int)`
quadEquation.cpp: In member function `int QuadEquation::getRoot1()`:
quadEquation.cpp:35: error: `discrim` was not declared in this scope
quadEquation.cpp:35: error: `getDiscrimant` was not declared in this scope
quadEquation.cpp: In member function `int QuadEquation::getRoot2()`:
quadEquation.cpp:40: error: `discrim` was not declared in this scope

1 个答案:

答案 0 :(得分:1)

您定义的其中一个构造函数是

QuadEquation::QuadEquation()
{
  int a,b,c;
}

但是这个构造函数没有在头文件中定义。此外,看起来这是你的错误,因为这个构造函数没有多大意义 - 它只是声明了三个局部变量而不使用它们中的任何一个。如果您确实要声明此构造函数,请将其添加到头文件中,但从您的代码判断我不认为这是必要的。

关于您的其他错误,请查看以下代码:

int QuadEquation::getRoot1()
{
  discrim = getDiscrimant();
  return -b + sqrt(discrim) / (2 * a);
}

有两件事突然袭来。首先,discrim在哪里宣布?其次,如果二次公式可以有任意复值根,那么你有没有理由返回int?你可以在这里使用不同的类型吗?

总的来说,您应该学会阅读这些编译器错误消息。我已经指出的所有内容都可以从错误输出中轻松收集到。现在您已经意识到问题所在,您能看到它们如何生成给定的编译器错误吗?

希望这有帮助!