Sponsored By

Sign in to follow this  
murtu52

Age Program

Recommended Posts

Well, I'm learning C++, and i am writing a program i saw on one of the tutorials. Basically, if you are younger than 50, it'll say you are young, if you are older than 50, it'll say you are old (I had to take out the if "age==50" to see if that was the problem or not; it isn't, and i don't want to put it back in because i'm afraid it'll mess up even more. Here is my source code:

#include <iostream>

using namespace std;

int main()

{

int age;

cout<<"Please enter your age \n";

cin>> age;

cin.ignore();

if (age>50){

cout<<"You are old!\n";

}

else (age<50);{

cout<<"Wow, you are young!\n";

}

cin.get();}

Basically, when i run the program, and say i'm older than 50 (For instance, i enter i'm 60) it prints both "You are old!" and "Wow, you are young!" My dad helped me figure out that it is ignoring the "else (age<50)" statement and printing the "Wow, you are young!" part, if the "if (age>50)" statement was true.

Anyone have any thoughts? I can't see any problems with it, but then again, i'm a beginner......

Share this post


Link to post
Share on other sites

Common error. Your problem is in the 'else' branch of the conditional. This:

else (age<50); {
   cout <<"Wow, you are young!\n";
}

is equivalent to this:

else {
   (age<50);
}
{
   cout << "Wow, you are young!\n"
}

What you have there is the single-statement (blockless) version of 'else' followed by a block with some deceptive formatting. You probably want:

else if (age<50) {
  cout << "Wow, you are young!\n"
}

or perhaps:

else {
  cout << "Wow, you are young!\n"
}

Edited by jcl

Share this post


Link to post
Share on other sites

I'm also in the learning stage of C++, but I would also suggest what jcl said as in:

else {
 cout << "Wow, you are young!\n"
}

because the other statement says that if they are over 50, to display "they are old" or something, all you need now is a statement for if they are NOT over 50, you do not have to defign what "not over 50" is (when you said if (age<50) ) that was not needed.

Hope that helps

Matt

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this