[英]My if-else statement does not work, does anyone know how to fix it?
Basically, I have a project due in about 2 days, and I cannot find how to make this if else
statement work.基本上,我有一个大约 2 天后到期的项目,我找不到如何使这个
if else
语句起作用。 I've done it before.我以前做过。 I do not know what I am doing wrong.
我不知道我做错了什么。
#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;
}
I do not know what this means:我不知道这是什么意思:
int response;
If you want to read a character, response
should be a char
not an int
.如果你想读取一个字符,
response
应该是一个char
而不是一个int
。
if (response == 'Y')
You forgot to actually read the user input.您忘记实际阅读用户输入。 Your compiler should have warned you for using
response
uninitialized.您的编译器应该警告您使用未初始化的
response
。
else (response == 'N')
This is the cause of the error you get.这是您得到错误的原因。
else
has no condition. else
没有条件。 else
is the case for "none of the other conditions are true
". else
就是“其他条件都不为true
”的情况。 You either want else if
or no condition here. else if
或没有条件,您要么想要else if
条件。
Correct code could look like this:正确的代码可能如下所示:
#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.