簡體   English   中英

Simpe if and else在C編程中

[英]Simpe if and else in C programming

我想讓該程序說,如果輸入1,屏幕將顯示“是G是G和弦中的第一個音符”,如果輸入其他任何內容,它將顯示“錯誤!”。 然后循環回到開始,這是我的嘗試。 另外,我知道有不同的方法來執行此操作,但這是針對學校作業的,並且枚舉數據類型是必需的,盡管此代碼對於僅顯示枚舉的使用而言意義非凡,但令我困擾的是我上班。 有指針嗎? (無雙關語)。

enum Gchord{G=1,B,D,};
int main(){
    printf( "What interval is G in the G chord triad \nEnter 1 2 or 3\n" );  
    int note;
    scanf("%i",&note);    

    if (note = 1 ){                 
        printf ("Yes G is %ist note in the G-chord\n",G )};
    else(
        printf("no, wrong");     
    return(0):       
};

note = 1被分配note與值1 您希望將note1進行比較,因此需要運算符== 在此處閱讀比較操作:

http://en.cppreference.com/w/cpp/language/operator_comparison

要明確:

note = 1;  // Assigning note to 1, note is now the value 1
note == 1; // Comparing note to 1, true if note is 1, false otherwise. 

您還遇到許多其他問題:

  • printf ("Yes G is %ist note in the G-chord\\n",G )}; 如果語句沒有,則行以分號結尾。
  • else( else不接受參數,應使用花括號else {
  • return(0) Return不是函數。

警告滿( -Wall )的編譯器將告訴您所有這些情況。 上面列表中的內容應該是編譯器錯誤。

您的代碼中存在很多問題,但主要的問題是因為您嘗試分配1note而不是comparission ==

另一件事是,您永遠不會檢查scanf是否有錯誤。

有括號和括號使用錯誤。

int main(){}應該至少是int main(void){}

return語句不應視為函數,不需要在(0)周圍加上這些括號,而應以Semicol結尾; 而不是:

現在,以下內容將更好地說明您可能嘗試做的事情:

#include<stdio.h>

enum Gchord{G=1,B,D,};

int main(void){
    printf( "What interval is G in the G chord triad \nEnter 1 2 or 3\n" );
    int note;

    if(scanf("%i",&note) == 1){
        if (note == 1 ){
            printf ("Yes G is %ist note in the G-chord\n",G );
        }else{
            printf("no, wrong");
        }
    }else{
        printf("Error, scanf\n");
    }
    return 0;
}
I don't know where to start. Your code has a lot of errors.
  • 代碼格式化:學習如何格式化代碼非常重要,這樣閱讀起來就更容易了。
  • int note; 變量幾乎總是應該在頂部聲明並初始化(在這種情況下, int note = 0;
  • 如果您使用分隔東西,在其后面輸入一個空格。 不是scanf("%i",&note); 但是scanf("%i", &note);
  • 要比較兩個值是否相等,請使用== 單個=用於為變量分配值。 錯誤: if (note = 1 )正確: if (note == 1)
  • 您將錯誤的括號用於else甚至無法關閉的括號。
  • 對於循環問題,您應該閱讀while loops然后再次詢問是否不了解它們。

     enum Gchord{G=1,B,D,}; int main() { int note = 0; printf("What interval is G in the G chord triad \\nEnter 1 2 or 3\\n"); scanf("%i", &note); if (note == 1) { printf ("Yes G is %ist note in the G-chord\\n", G); } else { printf("no, wrong"); } return 0; }; 

這里存在無數語法錯誤,其中包括每個人都指出的注釋:note = 1會將值1分配給note變量,而不是進行相等性測試。 您需要在這里==運算符。

另外,您實際上並沒有真正使用枚舉,您的老師可能不會在這方面讓您失望。

我對您的代碼進行了一些修改,以更多地使用枚舉並執行您要查找的循環。

enum Gchord { EXIT, G, B, D, };
int main()
{
    while (true)
    {
        printf("What interval is G in the G chord triad \nEnter 1, 2, 3, or 0 to exit\n");
        Gchord note;
        scanf("%i", &note);

        if( note == EXIT )
            break;

        if (note == G)
            printf("Yes G is %ist note in the G-chord\n", G);
        else
            printf("no, wrong\n");
    }

    return(0);
};

暫無
暫無

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

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