2014-09-27 147 views
-1

我是初學者,所以對我來說很簡單。我的問題在我的輸出中。如果你輸入一個全名,它會崩潰。我應該使用字符串以外的東西嗎?它正確地顯示輸出最初,但然後它也跑下來,並添加你是超重行,和一個額外的計算。如果計算加起來就是超重的用戶,它會很好地工作。另外,設置精度未被應用。我很難過。C++ BMI計算器問題

int main() 
{ 
    double height, weight, bmi; // height in inches, weight in pounds, bmi is total bmi of user 
    string name; // name of the user 
    int num; // the number 703 used for bmi calculation 
    num = 703; // constant used for bmi calculation 

    cout << "Please enter your full Name:"; // Asking the user to input their name 
    cin >> name; // Users name 

    cout << "Please enter your height(in inches):"; // User height in inches 
    cin >> height; // Users height 

    cout << "Please enter your weight(in lbs):"; //Users weight in lbs 
    cin >> weight; // Users weight 

    bmi = (weight/pow(height, 2)) * num; // the actual calculation of the bmi of the user 

    if (bmi >= 18.5 && bmi < 25) { 
     cout << name << " your BMI is " << setprecision(1) << bmi; // outputting to the user their actaul BMI 
     cout << endl; 
     cout << "You are in the optimal weight category!"; // outputting their category 
    } 

    else if (bmi < 18.5) { 
     cout << name << " your BMI is " << setprecision(1) << bmi; 
     cout << endl; 
     cout << "You are underweight."; 
    } 

    else (bmi >= 25); { 
     cout << name << " your BMI is " << setprecision(1) << bmi; 
     cout << endl; 
     cout << "You are overweight."; 
    } 

    return 0; 

} 
+0

也看看使用cin和[我們爲什麼會叫CIN清晰讀取輸入後CIN忽略](http://stackoverflow.com/問題/ 5131647 /爲什麼 - 會 - 我們叩CIN-明確和CIN-忽略,後讀輸入) – 2014-09-27 00:10:36

回答

0

cin使用空格作爲默認分隔符。因此,當您輸入「First Last」這樣的名稱時,cin >> name;只會使用「First」一詞,而cin >> height;會嘗試使用「Last」,您將遇到錯誤。如果您想允許全名,請嘗試使用std::getline

0

當您使用>>輸入一個字符串時,您只會得到一個的輸入。用戶的全名的其餘部分位於輸入緩衝器中,直到下一個輸入操作爲止,這可能是例如輸入一個整數。然後該文本作爲整數規範無效。

改爲使用getline來讀取一行文字。


順便說一句,爲了得到有關例如用作語句的純表達式(通常是錯誤的,並且在您的代碼中有一個例子),提高編譯器的警告級別。使用Visual C++使用/W4。用g ++使用-Wall

1

你必須在這條線的僞分號:

else (bmi >= 25); {