gpt4 book ai didi

将 char 数组转换为整数 C 编程

转载 作者:行者123 更新时间:2023-11-30 20:33:52 24 4
gpt4 key购买 nike

问题:用户输入 24 小时格式的时间。该阵列还以 24 小时格式列出了不同的时间。我想将用户输入的数字与最接近用户输入时间的时间进行比较。与用户输入的时间最接近的数字都将显示在屏幕上。我在公司工作了一整夜,并试图理解其背后的编程。谁能帮我?顺便说一句,我刚刚开始这门 C 编程类(class)。如果你看到任何看起来像 C# 代码的东西,那是因为我还没有学到足够的东西。这是我到目前为止所拥有的:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

int hours, mins; //24 hour time to be entered by user

int bestTime = scanf("%d:,%d", &hours, &mins); //best time for user departure

char* depart [8] = {"8:00", "9:43", "11:19", "12:47", "14:00", "15:45", "19:00", "\0"}; //times available for departure

int counter; //count number of times to loop
printf("Please Enter The Best Time For Your Flight In 24 Hour Format.\n");
scanf("%d:,%d", &hours, &mins);

for(counter = 0; counter < ; counter++){
if(bestTime < depart[counter]){
bestTime = depart[counter];
}
}

return bestTime;
}

最佳答案

您可以创建一个函数,将“hh:mm”格式的字符串转换为“00:00”的分钟数。然后用它来进行所有比较。

该函数的一种实现可以是

unsigned int str_to_mins(const char* t) {
return (unsigned int) (
((t[0] - '0') * 10 + (t[1] - '0')) * 60
+ (t[3] - '0') *10 + (t[4] - '0')
);
}

在所有字符串上调用此函数。他们会给你无符号整数。用它来查找最接近输入的数字。 (以类似的方式将您的输入也转换为这种格式)。

为了清楚起见,请将您的输入扫描为

char input[10];
scanf("%s", input);

关于将 char 数组转换为整数 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889006/

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