成员函数的意外返回值

时间:2014-03-03 18:29:20

标签: c++ constructor

我正在编写一个二次方程的程序,但是在程序的中间有一个错误,它总是返回0

这是我的代码

#include<iostream>
#include<math.h>
using namespace std;
class quardaticequation {
public:
    float a, b, c, sqr, descriminat;

    quardaticequation( float x, float y, float z ) {
        x = a;
        y = b;
        z = c;
    }

    //seems to always return 0 after use of contstructor
    float getDescriminant() {
        sqr = pow( b, 2.0 );
        sqr;
        descriminat = sqr - 4 * ( a * c);
        return descriminat;
    }
};

int main() {
    float first, second, third;
    cout << "please enter the number in float format";
    cin >> first;
    cout << "please enter the second  number in float format";
    cin >> second;
    cout << "please enter  the third number in float format";
    cin >> third;
    quardaticequation q( first, second, third );
    cout << q.getDescriminant(); //ALWAYS RETURNS 0
    return;
}

3 个答案:

答案 0 :(得分:4)

你的构造函数不对吗?

quardaticequation(float x,float y,float z){
    x=a;
    y=b;
    z=c;
}

应该是

quardaticequation(float x,float y,float z){
    a=x;
    b=y;
    c=z;
}

答案 1 :(得分:3)

构造函数中的值赋值存在错误:

x=a;
y=b;
z=c;

应该是

a=x;
b=y;
c=z;

如其他成员所建议的更好的是使用初始化列表:

quardaticequation(float x,float y,float z)
: a(x), b(y), c(z)
{
}

答案 2 :(得分:3)

该行

sqr;

绝对没有,也不应该在你的程序中。

这不起作用的原因是因为构造函数中有错误。看一下在哪里分配的内容。

相关问题