LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Program keeps giving me different answers (https://www.linuxquestions.org/questions/linux-newbie-8/program-keeps-giving-me-different-answers-4175427056/)

carlosk711 09-13-2012 08:14 AM

Program keeps giving me different answers
 
Whenever I type in 1994 and M it will give me one answer then I do it again and its different

#include <iostream>
using namespace std;
int main ()
{
int yr;
char gender;
int yrd;
yrd = ( 2012 ) - yr ;
cout << "Enter your year of birth:" << endl;
cin >> yr ;
cout << "Enter your Gender(M/F):" << endl;
cin >> gender ;
if ( ( gender == 'M') && yr <= 2012)
cout << "You will die in " <<(75 - yrd ) * (365 * 24 *60 *60) << "seconds" << endl;
else if (( gender == 'F') && yr <= 2012)
cout << "You will die in " << (80 - yrd ) * ( 365 * 24 * 60 *60) <<" seconds" << endl;

else
cout << "Your input was invalid you idiot. Run the program again!" << endl;


return 0;
}

crabboy 09-13-2012 08:45 AM

Your problem is you are doing the yrd calculation before the user enters his input.

Code:


#include <iostream>
using namespace std;
int main ()
{
  int yr;
  char gender;
  int yrd;
  long die;
  int mf = 0;

  cout << "Enter your year of birth:" << endl;
  cin >> yr ;
  cout << "Enter your Gender(M/F):" << endl;
  cin >> gender ;

  yrd = ( 2012 ) - yr ;
  if ( ( gender == 'M') && yr <= 2012)
      mf = 75;
  else if (( gender == 'F') && yr <= 2012)
      mf = 80;
  else
      cout << "Your input was invalid you idiot. Run the program again!" << endl;
  die = (( mf - yrd ) * ( 365 * 24 * 60 * 60 ));
  cout << "You will die in " << die << "seconds" << endl;


return 0;
}


Snark1994 09-13-2012 08:56 AM

Use [CODE][/CODE] tags around your code to make it more legible.

The problem is here:

Code:

//...
    int yr;
//...
    int yrd;
    yrd = ( 2012 ) - yr ; //'yr' has no value!
    cout << "Enter your year of birth:" << endl;
    cin >> yr ;

You're running the line to set yrd before you've assigned a value to yr, so you're going to get unpredictable behaviour! A good habit to get into is always assigning a value to variables before using them, and that way you will at least have a predictable (read: more easily found) bug.

EDIT: oops, beaten by crabboy... Sorry :D

carlosk711 09-13-2012 10:03 AM

it still comes out with random answers, where should I move it?

johnsfine 09-13-2012 10:14 AM

Quote:

Originally Posted by carlosk711 (Post 4779488)
it still

How are we supposed to guess what your program looks like now?

I assume you changed something based on the earlier answers you got. But I don't know what you changed.

Also, did you remember to recompile the program after changing the source code? Maybe you are still running the earlier version.


All times are GMT -5. The time now is 07:36 AM.