#include <time.h> #include <stdio.h> int main( ) { int n,m; time_t tmp_time; struct tm *ptime; tmp_time = time(NULL);//获取当前时间 ptime = localtime(&tmp_time); //输入进入时间 printf("%d-%d-%d %02d:%02d:%02d\n",(1900+ptime->tm_year),(1+ptime->tm_mon),ptime->tm_mday,\ ptime->tm_hour,ptime->tm_min,ptime->tm_sec); scanf("%d",&n);//停车时长 m=n/60; n=n%60; if(ptime->tm_min+n>=60)//分钟 { ptime->tm_min+=(n-60); n=(m+1)/24; m=(m+1)%24; if(ptime->tm_hour+m>=24)//小时 { ptime->tm_hour+=(m-24); m=(n+1)/30; n=(n+1)%30; if(ptime->tm_mday+n>30)//天 { ptime->tm_mday+=(n-30); n=(m+1)/12; m=(m+1)%12; if(ptime->tm_mon+m>12)//月 { ptime->tm_mon+=(m-12); ptime->tm_year+=(1+n); } else { ptime->tm_mon+=m; ptime->tm_year+=n; } } else ptime->tm_mday+=n; } else ptime->tm_hour+=m; } else ptime->tm_min+=n; //输入离开时间 printf("%d-%d-%d %02d:%02d:%02d\n",(1900+ptime->tm_year),(1+ptime->tm_mon),ptime->tm_mday,\ ptime->tm_hour,ptime->tm_min,ptime->tm_sec); return 0; }优化
时间: 2024-02-15 18:04:02 浏览: 64
这段代码是一个简单的停车计费程序,用户输入停车时长,程序会根据当前时间计算出离开时间并输出。这里有一些可以优化的地方:
1. 时间计算可以简化。可以直接将停车时长加到当前时间上,然后再将时间转换为年、月、日、小时、分钟、秒的形式输出。这样比逐个字段进行计算更加方便。
2. 可以进行输入合法性检查。用户输入停车时长时,应该检查是否输入了负数或非数字字符。对于非法输入应该给出相应的提示。
下面是一个优化后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
time_t current_time = time(NULL);
struct tm *current_tm = localtime(¤t_time);
// 输出当前时间
printf("Current time: %04d-%02d-%02d %02d:%02d:%02d\n",
current_tm->tm_year + 1900, current_tm->tm_mon + 1, current_tm->tm_mday,
current_tm->tm_hour, current_tm->tm_min, current_tm->tm_sec);
// 输入停车时长
int parking_time;
printf("Enter parking time (in minutes): ");
if (scanf("%d", &parking_time) != 1 || parking_time < 0)
{
printf("Invalid input!\n");
return 1;
}
// 计算离开时间
time_t leaving_time = current_time + parking_time * 60;
struct tm *leaving_tm = localtime(&leaving_time);
// 输出离开时间
printf("Leaving time: %04d-%02d-%02d %02d:%02d:%02d\n",
leaving_tm->tm_year + 1900, leaving_tm->tm_mon + 1, leaving_tm->tm_mday,
leaving_tm->tm_hour, leaving_tm->tm_min, leaving_tm->tm_sec);
return 0;
}
```
阅读全文