2011-05-12 28 views
2

我在編程工作了Bjarne Stroustrup的第3章:原理與實踐使用C++如何在C++中調用錯誤?

提示用戶輸入年齡或接收方,並將其分配給一個int變量 年齡。讓你的節目寫下「我聽說你剛剛過生日 而你已經年滿歲了。」如果年齡爲0或更少,或者110或更多,請致電 錯誤(「您在開玩笑!」)。

cout<<"Enter the age of "<<friend_name<< ".\n"; 
int age=0; 
cin>>age; 
if (age==0) 
    cout<<"you're kidding!"; 

if (age>=110) 
    cout<<"you're kidding!"; 

if (age!=0, 110) 
    cout<<"I hear you just had a birthday and you are " <<age<< " years old.\n"; 

我試圖做上面的代碼,但它不停地給我

「你在開玩笑吧!我聽你的,你剛纔有一個生日,你是0歲」

但我不認爲這是正確的。我認爲它應該做一個或另一個,而不是兩個,但我不知道如何做到這一點。

+0

閱讀同一本書中的「else if」。 – 2011-05-12 15:26:28

回答

6
if (age!=0, 110) 

那不適合條件語法。你需要做的:

if (age != 0 && age < 110) 
7

if (age!=0, 110)是你的問題。逗號運算符返回最右邊的表達式,以便代碼等於if(110)

4

一個問題是:if (age!=0, 110)。那不是你想象的那樣。如果你想歲的考驗大於零且小於110的測試將是:

if ((age > 0) && (age < 110)) 

而且,問題說明說你要輸出「你在開玩笑吧」爲負的年齡了。你沒有處理。

1
#include <iostream> 
using namespace std; 
int main() 
{ 
    int age; 
    cout <<"Enter age of the recipient:\n"; 
    cin >> age; 
    if (age != 0 && age < 110) 
    { 
     cout <<"I hear you just had a birthday and you are "<<age<<" years old.\n"; 
    } 
    else 
    { 
     cout <<"Youre kidding.\n"; 
    } 

} 

此代碼幫助?

0
#include <iostream> 
#include <cmath> 
#include <string> 
#include <algorithm> 
#include <vector> 
using namespace std; 
int main(){ 
cout<< "Write the age of the recipient\n"; 
int age; 
cin>>age; 
if(age<=0 || age>=110){ 
    cout<<"you're kidding!"<<endl;} 
else{ 
cout<< " I hear you just had a birthday and you are "<<age<< " years old."; 
} 

return 0; }