繁体   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