我继续学习C编程,今天我遇到了一个问题.在我的程序,用户必须输入以分钟为一个时间值,我的程序会计算它秒(很简单,实际上).但我想制定一个规则,那个时间不能是负面的.所以我使用了这段代码:
if(a<=0)
{
printf("Time cannot be equal to, or smaller than zero, so the program will now terminate\n");
exit(EXIT_FAILURE);
}
Run Code Online (Sandbox Code Playgroud)
但现在,我不想终止我的程序,我希望它返回到用户必须输入值时的状态.
我有我的终止程序的问题,但是一些搜索帮助了我,但我没有得到任何结果搜索如何重新启动我的程序.
这是我的程序的文本(我在Linux上工作):
#include<stdio.h>
#include<stdlib.h>
main()
{
float a;
printf("\E[36m");
printf("This program will convert minutes to seconds");
getchar();
printf("Now enter your time in minutes(e.g. 5):");
scanf("%f", &a);
printf("As soon as you will press the Enter button you`ll get your time in seconds\n");
getchar();
getchar();
if(a<=0)
{
printf("Time cannot be equal to, or smaller than zero, so the program will now terminate\n");
printf("\E[0m");
exit(EXIT_FAILURE);
}
else
{
float b;
b=a*60;
printf("\E[36m");
printf("The result is %f seconds\n", b);
printf("Press Enter to finish\n");
getchar();
}
printf("\E[0m");
}
Run Code Online (Sandbox Code Playgroud)
PS我不知道如何正确命名这个函数,所以我称之为重启,也许它有一个不同的名字?
已经发布的解决方案都有效,但我个人更喜欢这个apporach:
// ...
printf("Now enter your time in minutes(e.g. 5):");
scanf("%f", &a);
while(a <= 0){
printf("Time cannot be equal to, or smaller than zero, please enter again: ");
scanf("%f", &a);
}
Run Code Online (Sandbox Code Playgroud)
我认为它更清楚,它提供了一个错误消息和一个彼此独立的常规消息的机会.
| 归档时间: |
|
| 查看次数: |
12592 次 |
| 最近记录: |