如果是其他逻辑|金字塔错误

时间:2018-01-30 02:28:52

标签: c if-statement cs50

我正在尝试构建一个打印右对齐金字塔的c程序,即:

   ## 
  ### 
 #### 
##### 

我考虑过使用if-else逻辑来测试用户输入。但是,当我运行我的代码时,它一直给我这个错误,并且在输入无效时也不显示错误。

mario.c:25:2: else error: expected '}'
}
 ^
mario.c:7:1: note: to match this '{'
{

以下示例代码:

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


int main (void)
{
    int height;
    height = get_int("Enter a number between 0 and 23: "); // keep prompting user for valid input'

    if (height > 0 || height < 23) {
        for ( int levels= 1 ; levels <= height; levels++) {
            for (int spaces = height-levels; spaces > 0; spaces--){
                printf (" ");
            }
            for (int hash = 1; hash <= levels+1; hash++){
                printf ("#");
            }
            printf("\n");
        }
        else 
        {
            height = get_int("Please try again: ");
        }

    }
}

感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

此处排在if (height > 0 || height < 23)行,您目前正在使用||。由于您希望两个条件同时为同时,因此您应使用&&代替||

条件应为if (height > 0 && height < 23)

答案 1 :(得分:1)

else不在正确的级别:

你有:

if (...)
{
    for (...) 
    {
       ...
    } 
    else  
    { 
        ***
    }
}


if (...)
{
    for (...) 
    {
       ...
    }
} 
else  
{ 
    ***
}

所以在原始代码中:

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

int main (void)
{
    int height;
    height = get_int("Enter a number between 0 and 23: "); // keep prompting user for valid input'

    /* as pointed by Rajeev Singh, the following || should be a && */
    if (height > 0 || height < 23) {
        for ( int levels= 1 ; levels <= height; levels++) {
            for (int spaces = height-levels; spaces > 0; spaces--){
                printf (" ");
            }
            for (int hash = 1; hash <= levels+1; hash++){
                printf ("#");
            }
            printf("\n");
        }
    }
    else 
    {
        height = get_int("Please try again: ");
    }
    return 0;
}