2011-05-12 59 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; }