1

I want to run the loop unless n>0 and less than 23. I have written the code below but it doesn't seem to be working. Although if I write one condition at a time the program works fine. But when I use the && operator it fails

#include<stdio.h>
#include<cs50.h>
int main(void)
{
    int i, j, k, n;
    do
    {
        printf("Height: ");
        n = GetInt();
    }
    while(n<0 && n>23);

    for (i = 1; i <= n; i++)
    {
        for (k = 1; k <= n - i; k++)
        {
            printf(" ");
        }

        for (j = 0; j <= i; j++)
        {
            printf("#");
        }
        printf("\n");
    }
}
4

2 回答 2

1

&& operator means both condition must be true at same time. n can't be less than zero and greater than 23 at same time and so your condition fails irrespective of any input given and stored in n.

Use OR operator instead.

do
{

....

}while(n<0 || n>23);

means continue in loop till EITHER of condition holds true.

于 2014-05-04T08:56:45.937 回答
1

您可能想要的是一个逻辑 OR:

while(n<0 || n>23);

因为 n 不能同时小于 0大于 23。但 n 可以是负数大于 23。

于 2014-05-04T08:57:38.860 回答