There are many ways to do this, this is the one closest to your own code:
#include <stdio.h>
int main() {
int y, m;
printf("Input number of months: ");
fflush(stdout);
scanf("%d", &y);
m = y % 12;
y = y / 12;
printf(" %i Year(s) \n %i Month(s)" , y, m);
return 0;
}
The key issue is that you updated the value of y
before m
had a chance to look at it. Note the order of your y=...
and m=...
. If you do y=y/12
first, that would update y
‘s value to the number of years and the remainder information is lost at this step and m
would always be 0. By getting m
from the y
that’s from the user’s input first, you avoid that issue.
Another minor issue is that there is no need to cast the value from y/12
to be int
since you are assigning that value to y
which is of type int
in the first place. Same applies to when you calculate m
, where a typo is also present.
As for the use of fflush
, you can refer to this question for details. Compile your code with/without this line to see the difference.
3
solved Why am I not getting the remainder for “m”?