This is due to format specifier %i
.
You may not observe any difference in behaviour %d
and %i
When used with a printf()
, but when used with scanf
the significance is obvious, that %i
takes an integer value as integer value with decimal, hex or octal type, based on some prefix, such that
if it begins with 0x
its taken a Hex, when preceded with 0
, its taken as an Octal value. When you use %d
in a scanf
, it assume the base 10.
So, you need to replace %i
with %d
.
Additionally, make a habit of standard library reading man pages of the functions that you are planning to use.
For example, scanf
, section "Conversions" states that,
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
Also in section "Return Value", it states,
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
Getting the return values from scanf
, and addition some error handling for unexpected return will save you a lot of pain going ahead.
Additional Inputs:
- Its usually preferred/recommended to name your function with verb (or an action) rather than anything that makes no sense.
For example,
int valueofN (struct date d);
int f(int year, int month);
int g(int month);
If I am reviewing your code, I don't know what this function does. Going ahead, name functions and other variables in such a way that it makes sense.
- Use compatible data types
For example,
long int N1 = valueofN (date1);
long int N2 = valueofN (date2);
N1
and N2
are of the data type long int
while valueofN()
is returning an int
. Its a different data type, there is no immediate harm with this code, but there is a potential harm in this practice going ahead.
- Some improvement
This
int valueofN (struct date d)
{
int N;
return N = (1461 * (f(d.year, d.month) / 4) + 153 * (g(d.month) / 5)+ d.day);
}
could have been
int valueofN (struct date d)
{
return (int)(1461 * (f(d.year, d.month) / 4) + 153 * (g(d.month) / 5) +d.day);
}
- Some more improvement: You should always validate the data entered by user (unless you don't know the lower and higher bound values). For example, user can enter
50
for month
. It isn't validated. Handle that at the input stage itself. Make that a habit.