首页 文章

使用“if”时,在C中重新启动程序

提问于
浏览
4

我继续学习C编程,今天我遇到了一个问题 . 在我的程序中,用户必须以分钟为单位输入时间值,我的程序将计算秒数(非常简单,实际上) . 但我想制定一个规则,那个时间不能是负面的 . 所以我使用了这段代码:

if(a<=0)
    {
        printf("Time cannot be equal to, or smaller than zero, so the program will now terminate\n");
        exit(EXIT_FAILURE);
    }

但现在,我不想终止我的程序,我希望它返回到用户必须输入值时的状态 .

我有一个终止我的程序的问题,但一些搜索帮助了我,但是我没有得到任何结果搜索如何重新启动我的程序 .

这是我的程序的文本(我在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");
}

附:我不知道如何正确命名这个函数,所以我称之为重启,也许它有一个不同的名字?

3 回答

  • 0

    您只需使用 do ... while 循环(包括您的程序源代码) .

    do {
        /* Get user input. */
    } while (a <= 0);
    

    或者 goto 语句也可以模拟循环(不鼓励初学者) .

    start:
        /* Get user input. */
        if (a <= 0)
            goto start;
    
  • 5

    已经发布的解决方案都有效,但我个人更喜欢这个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);
    }
    

    我认为它更清楚,它提供了一个错误消息和一个彼此独立的常规消息的机会 .

  • 0

    你可以试试if-else where:

    do
    {
    /* get user input*/
    if (a > 0)
        {
         /* ... */
        }
    else
       printf ("Time cannot be negative, please re-enter") 
    }while(<condition>);
    

    *条件可能会持续到您想要继续 .

相关问题