2016-05-15 20 views
0

一般に、私は "person"という名前のメソッドとそのメソッドを持っています:print:データを出力するために、is_better_thanはいくつかの最大値を探します。私は何が問題なのか理解できません。何かアドバイス?プログラムエラー。助言が必要です

#include <iostream> 
#include <string> 
#include <math.h> 
using namespace std; 

class person 
{ 
    private: 
     string name; 
     double weight; 
     double height; 

    public: 
     person(); //Constructor 

     bool is_better_than(person best); 
     void read(); 
     void print(); 

     void operator=(const person& b); //overloading operator 
}; 

person::person() 
{ 
    string name = ""; 
    double weight = 0; 
    double height = 0; 
} 

void person::print() 
{ 
    cout << name << "\nWeight: " << weight << "\nHeight: " << height << "\n"; 
} 

void person::read() 
{ 
    cout << "Please enter person's name: "; 
    getline(cin, this->name); 
    cout << "Please enter person's weight: "; 
    cin >> this->weight; 
    cout << "Please enter person's height: "; 
    cin >> this->height; 

    string remainder; 
    getline(cin, remainder); //clear the buffer 
} 

bool person::is_better_than(person best) 
{ 
    if ((this->weight/pow(this->height,2) >= best.weight/(pow(best.height,2))) || best.weight == 0) 
     return true; 

    return false; 
} 

// iperfortosi telesti = 
void person::operator=(const person & b) 
{ 
    this->name = b.name; 
    this->weight = b.weight; 
    this->height = b.height; 
} 

int main() 
{ 
    person maxBMI; 
    bool cont = true; 
    while (cont) 
    { 
     person newperson; 
     newperson.read(); 

     if (newperson.is_better_than(maxBMI)) 
      maxBMI = newperson; 

     cout << "More data? (y/n) "; 
     string answer; 
     getline(cin, answer); 

     if (answer != "y") 
      cont = false; 
    } 
    cout << "The person with maximum BMI (body mass index) is "; 
    maxBMI.print(); 
    return 0; 
} 

出力:

 
Please enter person's name: Name 
Please enter person's weight: 123 
Please enter person's height: 123 
More data? (y/n) n 
The person with maximum BMI (body mass index) is 
Weight: 1.7881e-307 
Height: 2.0746e-317 
+0

彼の体重と身長は、彼が期待していなかった奇妙なものだと思います。 – randominstanceOfLivingThing

+0

私は間違った出力を得ます –

+2

私のアドバイスは、*デバッガ*を使用して各命令を1回実行し、*変数の値を監視しています。 –

答えて

1

それはクラス変数にローカル変数に代入しないので、あなたのデフォルトのコンストラクタが動作しません。

person::person() 
{ 
    name = ""; 
    weight = 0; 
    height = 0; 
} 

またはより良い:それは次のようになります。あなたのデフォルトコンストラクタで

person::person() : name(""), weight(0.0), height(0.0) {} 

、クラス属性が初期化されていないままとbest.weightは動作しません、最初はゼロであると仮定。

+0

彼はデフォルトのコンストラクタを必要とします。名前は構築する必要はありませんが、高さと重量があります。 –

+0

これは今日、私がこのミス(コンストラクターのローカル変数)を見たのは2回目です。混乱している新しい本/ウェブサイトが出てきましたか、それとも1人のインストラクターか? –

+0

@MartinBonner、ああ、ずっと厳しい偶然があった。 :) – bipll

関連する問題