C++ 支持数学中常见的逻辑条件:
C++ 有以下条件语句:
使用该if语句指定在条件为 时要执行的 C++ 代码块为true。 注意 if是小写字母。大写字母(If 或 IF)将产生错误。 例如:
#include
using namespace std;
int main() {
if (20 > 18) {
cout << "20大于18哦!";
}
return 0;
}
演示:
如果if语句为假,则执行else
#include
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "不错.";
} else {
cout << "你真棒!";
}
return 0;
}
演示:
解释:20)大于 18,因此条件为false。因此,我们继续处理else条件并在屏幕上打印“你真棒”。如果时间小于 18,程序将打印“不错”。
如果if语句为假,则执行else if,else if也为假才执行else:
#include
using namespace std;
int main() {
int time = 22;
if (time < 10) {
cout << "川川菜鸟.";
} else if (time < 23) {
cout << "川川菜鸟我爱你.";
} else {
cout << "川川菜鸟真帅.";
}
return 0;
}
演示:
有一个 if else 的简写,它被称为三元运算符, 因为它由三个操作数组成。它可用于用一行替换多行代码。它通常用于替换简单的 if else 语句。 语法:
variable = (condition) ? expressionTrue : expressionFalse;
而不是写:
#include
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "小了";
} else {
cout << "大了.";
}
return 0;
}
你可以简单地写:
#include
using namespace std;
int main() {
int time = 20;
string result = (time < 18) ? "小了." : "大了.";
cout << result;
return 0;
}
演示:
划重点:
string result = (time < 18) ? "小了." : "大了.";
如果time小于18,则执行小了,否则执行大了。就相当于一个if…else语句。
粉丝群:813269919