簡體   English   中英

我的 if-else 語句不起作用,有人知道如何解決嗎?

[英]My if-else statement does not work, does anyone know how to fix it?

基本上,我有一個大約 2 天后到期的項目,我找不到如何使這個if else語句起作用。 我以前做過。 我不知道我做錯了什么。

#include <iostream>
using namespace std;

int main()
{
    int response;
    cout << "is your circuit a parallel circuit?";

    if (response == 'Y')
    {
        cout << "yes";
    }
    else (response == 'N')
    {
        cout << "no";
    }
    return 0;
}

我不知道這是什么意思:

圖片

int response;

如果你想讀取一個字符, response應該是一個char而不是一個int

 if (response == 'Y')

您忘記實際閱讀用戶輸入。 您的編譯器應該警告您使用未初始化的response

 else (response == 'N')

這是您得到錯誤的原因。 else沒有條件。 else就是“其他條件都不為true ”的情況。 else if或沒有條件,您要么想要else if條件。

正確的代碼可能如下所示:

#include <iostream>
int main() {
    char response;
    std::cout << "is your circuit a parallel circuit?";
    std::cin >> response;
    if (response == 'Y') {     
        std::cout << "YES";
    } else if (response == 'N') {
        std::cout << "NO";
    } else {
        std::cout << "invalid input";
    }
}

暫無
暫無

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

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