The program is just simply supposed to calculate the users age by subtracting their dob from the current year. When I run the program it compiles successfully but I get a long number such as -215863352. The if and else conditions are added just to test them out, I was writing various programs using them to make sure I understand the syntax in c. I figure I'm missing something simple but can't figure it out.
#include <stdio.h>
int main()
{
int year;
int cyear;
int age = cyear - year;
printf("Please enter the year you were born: \n");
scanf("%i", &year);
printf("Now enter the current year: \n");
scanf("%i", &cyear);
if (1 1 == 2){
printf("You must be %i", age);
}
else {
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
CodePudding user response:
You are calculating the age before the input is taken from the user. So the age
variable is storing a garbage value.
Solution:
Position the calculation of age after taking the input from user that is after taking input of cyear
using scanf. The correct code is given below
#include <stdio.h>
int main()
{
int year;
int cyear;
int age =0; //initialise with 0
printf("Please enter the year you were born: \n");
scanf("%i", &year);
printf("Now enter the current year: \n");
scanf("%i", &cyear);
age = cyear - year; //note the change here
if (1 1 == 2){
printf("You must be %i", age);
}
else {
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
CodePudding user response:
enter code here
#include <stdio.h>
int main()
{
long long int year;
printf("Please enter the year you were born: \n");
scanf("%lld",&year);
long long int cyear;
printf("Now enter the current year: \n");
scanf("%lld",&cyear);
long long int age = cyear-year;
if (1){
printf("You must be %lld", age);
}
else { printf("Now enter the current year: \n");
scanf("%lld",&cyear);
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}