gpt4 book ai didi

c - 关于在C中以特定格式打印数字的问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:55 24 4
gpt4 key购买 nike

C 语言编程问题:

We want to get a positive integer number in seconds and print it with format HH:MM:SS.

例如,如果我们得到 3600,我们必须打印 01:00:00。或 4201 -> 01:10:01(必须打印前面的 0)。我知道如何获取小时、分钟和秒数,但我的问题在于输出格式。

注意:我们不能使用任何与时间相关的函数(例如 time.h 函数、结构等),也不能使用 if 语句(以检查小时、分钟或秒数是否小于大于或等于 10)。我们应该怎么做?可能吗?

最佳答案

We want to get a positive integer number in seconds and print it with format HH:MM:SS.

I know how to get the hour and minute and second numbers but my problem is with the output format.

使用 "%02d" @user3121023 .

“2”最小 文本宽度。
"0" 导致 padding 使用 '0' 来弥补最小宽度。

printf("%02d:%02d:%02d", hour, minute, second);

更有趣的是如何打印所有int total。将其分解为 hour, minute, secondhour 的范围问题存在标志问题。

".2"最小 数字宽度。这应该与 hour 一起使用,以确保 -7 打印为“-07”而不是“-7”。

#define SECS_PER_MIN 60
#define MINS_PER_HOUR 60

// Print time, valid for all `int`
void print_hms(int total /* total seconds */) {
int sec = total%SECS_PER_MIN;
total /= SECS_PER_MIN;
int min = total%MINS_PER_HOUR;
total /= MINS_PER_HOUR;
int hour = total;

// use abs() to print negative, `min,sec` without a sign
printf("%0.2d:%02d:%02d", hour, abs(min), abs(sec));
}

示例

print_hms(0);
print_hms(3600 + 23*60 + 45);
print_hms(24*3600);
print_hms(-7*3600);
print_hms(INT_MIN);

00:00:00
01:23:45
24:00:00
-07:00:00
-596523:14:08

关于c - 关于在C中以特定格式打印数字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com