C程序一直要求正确的号码

时间:2017-01-08 21:07:17

标签: c loops cs50

代码编译正确,但每次运行时,都无法正常运行程序。

如果我把#小于23,它仍然要求我再试一次。 如果我第二次使用相同的数字,它就可以了。

如果我输的数字大于23,它会继续让我再试一次。

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int height;
    printf("What is the height of the pyramid?\n");
    height = get_int();

    do {
        printf("The pyramid cannot be higher than 23 feet!\n");
        printf("Try again!\n");
        printf("What is the height of the pyramid?\n");
        height = get_int(); }
    while (height > 23);

    if (height <= 23) {
        printf("The height of the pyramid is %d feet high!\n", height);
    }
}

2 个答案:

答案 0 :(得分:2)

循环应该是:

while (height > 23) {
    printf("The pyramid cannot be higher than 23 feet!\n");
    printf("Try again!\n");
    printf("What is the height of the pyramid?\n");
    height = get_int();
}

使用do-while,做了两件事:

  1. 您先接受输入。 height = get_int();
  2. 进入do-while而不检查年龄是否大于23.然后再次要求输入height = get_int(); }

答案 1 :(得分:1)

根据Bandi Kishore的回答,金字塔的高度也不能低于1.

                        // ↓this part
while (height > 23 || height < 1) {
    printf("The pyramid should be between 1 and 23 feet high (not %d feet)\n", height);
    printf("Try again!\n");
    printf("What is the height of the pyramid?\n");
    height = get_int();
}

CS50问题应该是https://cs50.stackexchange.com/