How do you call error in C++?
I'm working on Bjarne Stroustrup's Chapter 3 in Programming: Principles and Pr开发者_如何学编程actice Using C++
Prompt the user to enter the age or the recipient and assign it to an int variable age. Have your program write "I hear you just had a birthday and You are age years old." If age is 0 or less or 110 or more, call error("you're kidding!").
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";
I tried to do the code above but It kept giving me
"you're kidding! I hear you you just had a birthday and you are 0 years old"
but I don't think that is right. I think it's supposed to do one or the other and not both but I don't know how to make it do that.
if (age!=0, 110)
is your problem. The comma operator returns the right-most expression, so that code is equivalent to if(110)
.
if (age!=0, 110)
Thats not proper syntax for a conditional. You need to do:
if ( age != 0 && age < 110 )
One problem is this: if (age!=0, 110)
. That's not doing what you think it is. If you want to test of the age is greater than zero and less than 110 the test would be:
if ((age > 0) && (age < 110))
Also, the problem specification says you are to output "you're kidding" for negative ages, too. You're not handling that.
#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";
}
}
Does this code help?
#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; }
精彩评论