在C中再次自动运行代码

时间:2017-09-21 17:31:18

标签: c

如果最初输入的值小于0或大于23,我希望用户能够立即重新输入另一个值。目前,我的代码输出"请重新输入小于24的值&# 34;并停止。然后必须再次运行它,然后用户才能重新输入另一个值。

{
    printf ("What is the height of the half-pyramids?\n");
        int height = get_int();
        if (height>23)
        {
            printf("please re-enter a value less than 24\n");
        }
        else if (height<0)
        {
            printf("please re-enter a value more than 0\n");
        }
        else
        {
            printf("%i", height);
    }

}

2 个答案:

答案 0 :(得分:2)

使用循环。

while(1) {
    printf ("What is the height of the half-pyramids?\n");
    int height = get_int();
    if (height>23)
    {
        printf("please re-enter a value less than 24\n");
    }
    else if (height<0)
    {
        printf("please re-enter a value more than 0\n");
    }
    else
    {
        printf("%d\n", height);
        break; // stop stop looping
}
顺便说一下,使用%d打印整数更加惯用,而不是%i。见What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

答案 1 :(得分:2)

你可以使用do-while循环:

do {
    printf ("What is the height of the half-pyramids?\n");
    int height = get_int();
    if (height > 23) {
        printf("please re-enter a value less than 24\n");
    } else if (height <= 0) {
        printf("please re-enter a value more than 0\n");
    }
    else {
        printf("%i", height);
    }
} while (height <= 0 || height > 23);