[Solved] Trying to calculate age in C


Expressions in C are not formulas. This:

int age = CurrentYear - BornYear;

Does not mean that the value of age will always be CurrentYear - BornYear. It means that at that point in the code, age is set to CurrentYear - BornYear based on the current value of those variables. Both of those variables are uninitialized, so their values are indeterminate.

You need to move the calculation of age to after you’ve read in CurrentYear and BornYear:

int CurrentYear;
int BornYear;
int age;

printf("What year is it?\n");
scanf("%d", &CurrentYear);
printf("What year you were born?\n");
scanf("%d", &BornYear);

age = CurrentYear - BornYear;
printf("You are %d years old\n", age);

2

solved Trying to calculate age in C