C语言程序设计现代方法第二版,第五章课后习题之——5.2小题"12小时制时间转换"

C语言程序设计现代方法第二版的官方源码地址及github地址:

http://knking.com/books/c2/answers/index.html

https://github.com/fordea/c-programming-a-modern-approach

/*
C语言程序设计现代方法第二版
第五章课后编程习题—— 5.2 小题 :仅供参考,欢迎赐教!
要求用户输入24小时制的时间,然后显示12小时制的格式
*/
#define AM "上午"
#define PM "下午"

#include 

int main(void) { 
    int hours, minutes;
	
	printf ("Enter a 24-hour time: \n");
	scanf ("%d:%d", &hours, &minutes);
	
	printf ("Equivalent 12-hour time: \n");
	
    // hours%24  便于判断上午还是下午,如果改成hours%12 会判断不准
    if( hours%24 < 12 ){
        hours %= 12;
        printf("%.2d:%.2d %s \n", hours, minutes, AM);
    }else if( hours%24 == 12 ){
        hours = 12;
        printf("%.2d:%.2d %s \n", hours, minutes, PM);
    }else if( hours%24 > 12 ){
        hours %= 12;
        printf("%.2d:%.2d %s \n", hours, minutes, PM);
    }
    
	return 0;
}

示例:

Enter a 24-hour time: 00:35
Equivalent 12-hour time: 
00:35 上午  

Enter a 24-hour time: 9:35
Equivalent 12-hour time: 
09:35 上午 

Enter a 24-hour time: 23:35
Equivalent 12-hour time: 
11:35 下午

Enter a 24-hour time: 24:35
Equivalent 12-hour time: 
00:35 上午

Enter a 24-hour time: 35:35
Equivalent 12-hour time: 
11:35 上午 

Enter a 24-hour time: 36:35
Equivalent 12-hour time: 
12:35 下午

Enter a 24-hour time: 37:35
Equivalent 12-hour time: 
01:35 下午 

 

你可能感兴趣的:(C语言现代方法)