gpt4 book ai didi

c++ - if 语句后跟 return 0

转载 作者:行者123 更新时间:2023-12-05 08:28:54 24 4
gpt4 key购买 nike

我有一些代码:

#include <iostream>
#include <string>

int main() {
std::string question;

std::getline(std::cin, question);

if (question == "yes") {
std::cout << "Let's rock and roll!" << std::endl;
return 0; // This line
} if (question == "no") {
std::cout << "Too bad then..." << std::endl;
} else {
std::cout << "What do you mean by that?" << std::endl;
}
return 0;
}

如果我不写注释 return 0 行并输入 yes,输出是 Let's rock and roll! 后跟 你这是什么意思?。它应该只输出 Let's rock and roll!

但我不需要将 return 0 放在 if (question=="no"){...} block 中。如果我输入 no,输出只是 Too bad then...

为什么在第一种情况下需要return 0,而在第二种情况下不需要?

最佳答案

控制流是您的问题:

     if(question == "yes"){
std::cout<<"Lets rock and roll!"<<std::endl;
return 0;
}if (question == "no"){
std::cout<<"Too bad then..."<<std::endl;
} else{
std::cout<<"What do you mean by that?"<<std::endl;
}

让我们通过用换行符包围 if/else 语句/ block 并在运算符周围添加一些空格来更好地格式化它。

     if (question == "yes") {
std::cout << "Lets rock and roll!" << std::endl;
return 0;
}

if (question == "no") {
std::cout << "Too bad then..." << std::endl;
}
else {
std::cout << "What do you mean by that?" << std::endl;
}

这是两个不同的条件。第一个被触发不会阻止第二个 if/else 被评估。事实上,如果 question 等于 "yes" 那么它不能等于 "no" 所以第二个 if/else 必须被执行。

通过在第一个条件 block 中包含 return 0;,函数立即退出,从而跳过它之后的所有内容。第二个 if/else 未被评估,“What do you mean by that?” 从未被打印。

您可能希望这是一个单独的 if/else。现在只会执行这些 block 中的一个。因为一个 else 包含在事件中作为一个包罗万象的事件,如果前面的条件都不满足,它保证一个分支将被执行。

     if (question == "yes") {
std::cout << "Lets rock and roll!" << std::endl;
}
else if (question == "no") {
std::cout << "Too bad then..." << std::endl;
}
else {
std::cout << "What do you mean by that?" << std::endl;
}

关于c++ - if 语句后跟 return 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73507769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com