开发一套网站多少钱,广州网站建设系统,wordpress 做图片,个人自己免费建网站目录
一、if语句
二、if else语句
三、格式化if else语句
四、if else if else结构 一、if语句
if语句让程序能够决定是否应执行特定的语句。
if有两种格式#xff1a;if和if else。
if语句的语法与while相似#xff1a;
if(test-condition)statement;
如果test-con…目录
一、if语句
二、if else语句
三、格式化if else语句
四、if else if else结构 一、if语句
if语句让程序能够决定是否应执行特定的语句。
if有两种格式if和if else。
if语句的语法与while相似
if(test-condition)statement;
如果test-condition测试条件为true则程序将执行statement语句后者既可以是一条语句也可以是语句块。如果测试条件为false则程序将跳过语句。和循环测试条件一样if测试条件也将被强制转换为bool值因此0将被转换为false非零为true。整个if语句被视为一条语句。
例如假设读者希望程序计算输入中的空格数和字符总数则可以在while循环中使用cin.get(char)来读取字符然后使用if语句识别空格字符并计算其总数。程序清单6.1完成了这项工作它使用句点.来确定句子的结尾。
//if
#if 1
#includeiostream
using namespace std;int main()
{char ch;int spaces 0;int total 0;cin.get(ch);//成员函数cin.get(char)读取输入中的下一个字符即使它是空格并将其赋给变量chwhile (ch ! .){if (ch )spaces;total;cin.get(ch);}cout spaces spaces, total characters total in sentence\n;//字符总数中包括按回车键生成的换行符system(pause);return 0;
}
#endif
二、if else语句
if语句让程序决定是否执行特定的语句或语句块而if else语句则让程序决定执行两条语句或语句块中的哪一条这种语句对于选择其中一种操作很有用。
if else语句的通用格式如下
if(test-condition)statement1
elsestatement2
如果测试条件为true或非零则程序将执行statement1跳过statement2如果测试条件为false或0则程序将跳过statement1执行statement2。
从语法上看整个if else结构被视为一条语句。
例如假设要通过对字母进行加密编码来修改输入的文本换行符不变。这样每个输入行都被转换为一行输出且长度不变。这意味着程序对换行符采用一种操作而对其他字符采用另一种操作。正如程序清单6.2所表明的该程序还演示了限定符std::这是编译指令using的替代品之一。
//if else
#if 1
#includeiostreamint main()
{char ch;std::cout Type, and I shall repeat.\n;std::cin.get(ch);//成员函数cin.get(char)读取输入中的下一个字符即使它是空格并将其赋给变量chwhile (ch ! .){if (ch \n)std::cout ch;elsestd::cout ch;//ASCII码std::cin.get(ch);}std::cout \nPlease excuse the slight confusion.\n;system(pause);return 0;
}
#endif
运行情况 三、格式化if else语句
if else中的两种操作都必须是一条语句。如果需要多条语句则需要用大括号将它们括起来组成一个块语句。
四、if else if else结构
程序清单6.3使用这种格式创建了一个小型测验程序。
#if 1
#includeiostream
using namespace std;
const int Fave 27;int main()
{int n;cout Enter a number in the range 1-100 to find;cout my favorite number: ;do{cin n;if (n Fave)cout Too low -- guess again: ;else if (n Fave)cout Too high -- guess again: ;elsecout Fave is right!\n;} while (n ! Fave);system(pause);return 0;
}
#endif