旁支语句和逻辑运算符
分支语句和逻辑运算符
一、if语句
1. if语句
statement 语句
test_expr 测试条件
false 假
true 真
语法:
如果测试条件为真,则程序将执行语句,后者既可以是一条语句,也可以是语句块。如果测试条件为假,怎程序将跳过语句。和循环测试条件一样,if测试条件也将被强制转换为bool值,因此0将被转换为false,非零为true。整个if语句被视为一条语句。
if.cpp
#include<iostream> int main() { using std::cin; using std::cout; char ch; int spaces = 0;//计算输入中的空格数 int total = 0;//计算字符总数 字符总数中包括按回车键生成的换行符 cin.get(ch);//读取字符 while (ch != '.'/*确定句子结尾*/) { if (ch == ' ') ++spaces; ++total; cin.get(ch);//读取字符 } cout << spaces << "spaces," << total; cout << "characters total in sentence\n"; cin.get(); cin.get(); return 0; }
输出
a b c d e f. 4spaces,11characters total in sentence
很明显输入了4个空格,所以4spaces,而11=6(字母)+4(空格)+1(回车)。
2. if else语句
statement 语句
test_expr 测试条件
false 假
true 真
if else if else结构
二、逻辑表达式
逻辑 OR 运算符:||
逻辑 AND 运算符:&&
用&&来设置取值范围
逻辑 NOT 运算符:!
三、字符函数库 cctype
四、 ?: 运算符
五、 switch 语句
六、 break 和 continue 语句