C++初学(16)

16.1、if语句

当C++程序必须决定是否执行某个操作时,通常使用if语句来实现选择。if有两种格式:if和if else。

if语句的语法与while相似:

if(text-condition)
  statement

如果text-condition(测试条件)为true,则程序执行statement(语句)。后者可以是一条语句,或者语句块。如果测试条件为false,则程序将跳过语句。与循环测试一样,if测试条件也将被强制转换为bool值,因此0将被转换为false,非零为true。

#include<iostream>
int main()
{
	using namespace std;
	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 ";
	return 0;
}

仅当ch为空格时,语句++spaces;才会被执行。因为语句++total;位于if语句的外面,因此在每轮循环中都将被执行。注意:字符总数中包括按回车键生成的换行符。

16.2、if else语句

if语句让程序决定是否执行特定的语句或语句块,而if else语句则让程序决定执行两条语句或语句块中的哪一条,这种语句对于选择其中一种操作很有用。if else语句的通用格式如下:

if (text-condition)
  statement1
else
  statement2

如果测试条件为true或非0,则程序将执行statement1,跳过statement2;如果测试条件为false或0,则程序跳过statement1,执行statement2。

#include <iostream>
int main()
{
	using namespace std;
	char ch;
	cout << "Type,and I shall repeart." << endl;
	cin.get(ch);
	while (ch != '.')
	{
		if (ch == '\n')
			cout << ch;
		else
			cout << ++ch;
		cin.get(ch);
	}
	cout << endl << "Please excuse the slight confusion." << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值