简体   繁体   English

输入用户的小时和分钟,并添加持续时间以显示更新的时间

[英]Input hour and minute from user, and add duration to display updated time

I need to write the program that accepts three integers as input (hour, minute, duration). 我需要编写接受三个整数作为输入(小时,分钟,持续时间)的程序。 Hour is in 24 hour format. 小时为24小时格式。 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 我的开始时间显示如下:当我输入12小时(小时)和52分钟(分钟)时,我的开始时间显示为

-2114693200:1. -2114693200:1。

Not sure why happens 不确定为什么会发生

missing arguments in printf() causing undefined behaviour. printf()中缺少参数会导致未定义的行为。

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. 您也不需要以24为模,除非您要将小时转换为天...如果您还需要存储和打印天数。

h=(h+ht)%24;

You did not supply the arguments to the format specifiers in printf() . 您没有在printf()为格式说明符提供参数。 It invokes undefined behavior . 它调用未定义的行为

Quoting C11 , chapter §7.21.6.1, fprintf() 引用C11 ,第§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. 也就是说,请始终检查scanf()的返回值以确保扫描成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM