鱼C论坛

 找回密码
 立即注册
查看: 587|回复: 1

[已解决]time

[复制链接]
发表于 2023-12-6 09:14:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
对于以下代码,请问有何修改意见,使其更加规范(在vscode里有报错信息,但不影响运行)
  1. #include <stdio.h>
  2. #include <time.h>

  3. void calculate(int *day,int *year)
  4. {
  5.     time_t time_s;
  6.     time_s = time(NULL);
  7.     *day = time_s / (24 * 60 * 60);
  8.     *year = time_s / (365*86400);
  9. }

  10. int main()
  11. {
  12.     time_t now;
  13.     int *time_d;
  14.     int *time_y;
  15.     now = time(NULL);
  16.     calculate(&time_d,&time_y);
  17.    
  18.     printf("%li\n",time_d);
  19.     printf("%li\n",time_y);

  20.     return 0;
  21. }
复制代码
最佳答案
2023-12-6 09:15:18
在代码中,你声明了两个int指针变量`time_d`和`time_y`,但是没有为它们分配内存,导致在使用时会引发错误。另外,`time_d`和`time_y`都是用来接收结果的变量,应该直接定义为int类型而不是指针。

此外,还可以进一步规范代码,包括删去无用的头文件(例如`#include <time.h>`)和其他冗余代码,确保代码更加简洁和易读。

以下是修改后的代码:
  1. #include <stdio.h>
  2. #include <time.h>
  3. void calculate(int *day, int *year) {
  4.     time_t time_s;
  5.     time_s = time(NULL);
  6.     *day = time_s / (24 * 60 * 60);
  7.     *year = time_s / (365 * 86400);
  8. }
  9. int main() {
  10.     int time_d;
  11.     int time_y;
  12.     calculate(&time_d, &time_y);
  13.    
  14.     printf("%d\n", time_d);
  15.     printf("%d\n", time_y);
  16.     return 0;
  17. }
复制代码

这样修改后,代码更加规范且运行正常。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-12-6 09:15:18 | 显示全部楼层    本楼为最佳答案   
在代码中,你声明了两个int指针变量`time_d`和`time_y`,但是没有为它们分配内存,导致在使用时会引发错误。另外,`time_d`和`time_y`都是用来接收结果的变量,应该直接定义为int类型而不是指针。

此外,还可以进一步规范代码,包括删去无用的头文件(例如`#include <time.h>`)和其他冗余代码,确保代码更加简洁和易读。

以下是修改后的代码:
  1. #include <stdio.h>
  2. #include <time.h>
  3. void calculate(int *day, int *year) {
  4.     time_t time_s;
  5.     time_s = time(NULL);
  6.     *day = time_s / (24 * 60 * 60);
  7.     *year = time_s / (365 * 86400);
  8. }
  9. int main() {
  10.     int time_d;
  11.     int time_y;
  12.     calculate(&time_d, &time_y);
  13.    
  14.     printf("%d\n", time_d);
  15.     printf("%d\n", time_y);
  16.     return 0;
  17. }
复制代码

这样修改后,代码更加规范且运行正常。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-11 14:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表