我正在爲二次方程編寫一個類。我已經得到.h文件,並且必須根據它來編寫它。我遇到問題時,我試圖建立的「顯示」功能,在這裏我得到未聲明的標識符區域(如下圖所示):在使用C++編寫類時遇到問題;未聲明的標識符
「my_a」:未聲明的標識符
「my_b」:未聲明的標識符
「my_c」:未聲明的標識符
「顯示器」:函數式初始化似乎是一個函數定義
我希望在我的代碼一點方向。我在底部包含.h文件。
#include <iostream> // for cout, cin, istream, ostream
#include <cmath> // for floor
#include <string> // for class string
#include "quad.h"
using namespace std;
quadraticEquation::quadraticEquation (double initA,
double initB, double initC)
{
my_a = initA;
my_b = initB;
my_c = initC;
}
double quadraticEquation:: root1() const
{
double result = 0.0;
result= ((-1* my_b)+(sqrt((my_b*my_b)- (4*my_a*my_c)))/(2*my_a));
return result;
}
double quadraticEquation:: root2() const
{
double result = 0.0;
result= ((-1*my_b)- (sqrt((my_b*my_b)- (4*my_a*my_c)))/(2*my_a));
return result;
}
bool hasRealRoots(double root1 , double root2)
// post: returns true if an only if b*b-4*a*c >= 0.0, otherwise return false
{
bool result;
{
if (root1 >= 0.0) {
if (root2 >= 0.0){
result = true;
}
else
{
return false;}
}
}
}
void display (my_a, my_b, my_c)
// post: shows the quadratic equation like -1x^2 + 3x - 9.7
// when my_a == -1, my_b = 3, and my_c == -9.7
{
if (my_a >= 0)
cout <<my_a<< "x^2"<<;
else
cout <<"-"<< abs(my_a)<<"x^2"<<;
if(my_b >= 0)
cout << " + " << my_b << "x";
else
cout << " - " << abs(my_b) << "x";
if (my_c >= 0)
cout <<" + "<<my_c<< endl;
else
cout << " - "<<my_c<< endl;
return display;
}
而且
#ifndef _QUAD_H
#define _QUAD_H
// file name: quad.h (the file on disk lists pre- and post-conditions)
class quadraticEquation {
public:
//--constructor (no default constructor for quadraticEquation)
quadraticEquation(double initA, double initB, double initC);
// post: initialize coefficients of quadratic equation initA*x*x + initB + c
//--accessors
double root1() const;
// pre: there is at least one real root: b*b-4*a*c >= 0.0
// post: returns one real root as (-b+sqrt(b*b-4*a*c))/(2*a)
double root2() const;
// pre: there is at least one real root: b*b-4*a*c >= 0.0
// post: returns one real root as (-b-sqrt(b*b-4*a*c))/(2*a)
bool hasRealRoots() const;
// post: returns true if an only if b*b-4*a*c >= 0.0, otherwise return false
void display() const;
// post: shows the quadratic equation like -1x^2 + 3x - 9.7
// when my_a == -1, my_b = 3, and my_c == -9.7
private:
double my_a, my_b, my_c; // the three coefficients of the quadratic equation
};
#endif
更好是'一元二次方程::一元二次方程(雙INITA, 雙INITB,雙initC):my_a( initA),my_b(initB),my_c(initC){}'作爲構造函數。這是更習慣的C++。 – wheaties 2011-06-15 13:02:26
我也更喜歡'返回[公式];'到整個使用的三行版本,但毫無疑問,教授指示他們故意使用這個習語。 – 2011-06-15 13:13:12