簡體   English   中英

CS50,預設 1,Mario More Comfortable - 錯誤:預期的表達

[英]CS50, Preset 1, Mario More Comfortable - Error: Expected Expression

我正在為 CS50、Mario More Comfortable 開發預設 1。 我一直在嘗試編譯以下代碼,但收到“錯誤:預期表達式”消息。 我檢查了拼寫、分號、方括號和圓括號,但一切似乎都井井有條。 想法?

代碼:

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

int main(void)

{
    // declare h

    int h;

    // get integer (user input) between 1 and 8, inclusive
do
{
    h = get_int("Height: \n");

    // if integer is greater than 8 or less than 1, prompt the user again until they enter a valid input
}while(h > 8 || h < 1);

        // outer loop uses i to print a row of bricks h times
        for (int i = -1; i < h; i++)
        {
            // inner loop uses j to print a column h times
            for (int j = 0; j <= h; j++)
            {

                // e.g. if 8 + 8 > (8 - 1), print hash; else print blank: right-aligns
                if (i + j > (h - 1))
                {
                    printf("#");
                }

                printf("  ");

                // e.g. if 8 + 8 < (8 - 1), print hash; else print blank: left-aligns
                else if (i + j < (h - 1))
                {
                    printf("#");
                }

            }

            printf("\n");
        }
    }

錯誤信息:

error: expected expression
                else (i + j < (h - 1))

本次練習的預期結果:

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

你有錯誤是因為else if

if 語句向計算機提供檢查條件並繼續執行大括號 {} 內的語句。 當您退出這些大括號並編寫另一個語句或表達式時,您基本上就放棄了條件檢查。 之后如果你想檢查一個條件,你應該再次使用if 您可以在if語句之后立即使用else if來檢查另一個條件是否有價值。

h = 5;
x = 3;
if (h < x)
    printf("h is less than x\n");
x = 10;

if (h < x)
    printf("h is less than x\n");
else if (h > x)
    printf("h is bigger than x\n);
else
    printf("h is equal to x\n");

該程序將檢查第一個if條件而不是評估表達式x = 10然后繼續閱讀下一行並使用新值檢查第二個if條件,然后檢查else if和稍后的else

在我解決這個問題后,我檢查了你的代碼,它沒有給出金字塔而是方形打印。 如果您還沒有解決這個問題集,請嘗試添加printf(" "); 打印空間以創建金字塔形狀。 邏輯是在增加# 的大小的同時減少空格的大小。 如果您更改for循環條件,您可以獲得所需的結果。 當您遞減第一個循環時,您可以遞增嵌套循環。 第一個循環將打印一個向下的空間金字塔,而第二個循環將打印一個向上的#金字塔。 希望有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM