gpt4 book ai didi

c - 如何让我的时钟应用程序运行

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

我想制作一个像大多数计时器应用程序或煮蛋计时器一样根据用户输入运行的计时器。我编写了代码,但我想出了垃圾值和几乎无法工作的代码。请帮忙!

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

main(){
int h=0;
int s=0;
int m=0;
printf("Please enter the time you want for the timer.");
printf("Please enter how many hours you want for the timer.(max 24!)");
scanf("%d",&h);
printf("Please enter how many minutes you want for the timer.(max 59!)");
scanf("%d",&m);
printf("Please enter how many seconds you want for the timer.(max 59!)");
scanf("%d",&s);

while (s<=60){

printf(" %d hours %d minutes and %d seconds \n", m ,s);//gives the countdown output
sleep(1); //for delaying in seconds.
s++;// adds one to the second counter

if(s==60){
m++;//adds one to the second counter when seconds reach 60
s=0;//resets seconds value to 0.
}
if(m==60){
h++;
m=0;
}
if(h==24){
printf("The timer has reached Max output!\n");
break;
}
}



getch();
}

最佳答案

主要问题在于

 printf(" %d hours %d minutes and %d seconds \n", m ,s);

这里,您向 printf() 提供了三个格式说明符,但只传递了两个参数!这会调用 undefined behavior .

引用 C11,第 §7.21.6.1 章,fprintf()

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined.

话虽这么说,我认为你应该重新设计该方法。这应该是一个倒计时计时器,因此从给定值开始,并尝试使所有变量达到零。应该有递减,而不是增量

此外,不要期望用户遵守屏幕上的说明(例如>(最多 59!)),请验证自己输入。不要忘记检查 scanf() 的返回值。

关于c - 如何让我的时钟应用程序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595608/

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