scanf ("%2d %2d", &shours, &sminutes);
printf ("Enter End Time : ");
scanf ("%2d %2d", &ehours, &eminutes);
printf ("\nTIME DIFFERENCE\n");
tohours = ehours - shours;
printf("Hour(s) : %2d", tohours);
tominute = eminutes - sminutes;
printf("\nMinute(s): %2d ", tominute);
如何使我的输出像这样?当我尝试运行代码时,分钟输出为-59而不是1,而我的小时数则为输出“ 1”
P.S。不使用if else语句
答案 0 :(得分:1)
使用(某种形式的)时间戳记,将小时和分钟变量变成一个,例如:
stime = shours * 60 + sminutes;
etime = ehours * 60 + eminutes;
然后计算该差值
totime = etime - stime;
然后将其转换为小时和分钟
tominutes = totime % 60;
tohours = (totime - tominutes) / 60;
(整数部分将四舍五入)
不是最详尽的解决方案,但我想您正在寻找对初学者友好的解决方案
修改
谈到初学者:%是返回除法运算余数的模运算符。因此,当您将119除以60时,它会返回59。是的,您也可以得到将 totime 除以60的小时数,然后让整数除法完成工作,但是效果更好(阅读:划分(totime-tominutes)时,请阅读发生的情况),因为这就像模数行中缺少的部分