Reputation: 175
I need to write the program that accepts three integers as input (hour, minute, duration). Hour is in 24 hour format. The hour and minute should be considered the start time, and duration should be in minutes. You should then calculate the end time and display it properly in the format ##:##
. This is what I got but my Starting time displays weird.
#include <stdio.h>
int main(int argc, char *argv[])
{
int h=0,m=0,d=0,ht=0,t=0;
printf("Starting Hours: ");
scanf("%d",&h);
printf("Starting Minutes: ");
scanf("%d",&m);
printf("Starting Time is %d,%d ,What is the duration");
scanf("%d",&d);
t=(m+d);
ht=t/60;
h=(h+ht)%24;
m=t%60;
printf("Ending Time: %d:%d",h,m);
getchar();
return 0;
}
My starting time displays something like this: when I enter 12 for hours, and 52 for min my Starting time displays as
-2114693200:1.
Not sure why happens
Upvotes: 0
Views: 506
Reputation: 2303
missing arguments in printf() causing undefined behaviour.
printf("Starting Time is %d,%d ,What is the duration");
it should be
printf("Starting Time is %d,%d ,What is the duration",h,m);
You also don't need to modulo by 24 unless you want to convert hour to days... if you want that you need to store and print number of days as well.
h=(h+ht)%24;
Upvotes: 1
Reputation: 134286
You did not supply the arguments to the format specifiers in printf()
. It invokes undefined behavior.
Quoting C11
, chapter §7.21.6.1, fprintf()
[...] If there are insufficient arguments for the format, the behavior is undefined. [...]
You need to write
printf("Starting Time is %d,%d ,What is the duration", h, m);
That said, always check for the return value of scanf()
to ensure the scanning is success.
Upvotes: 0