C/C++ if / if...else / if...else if... else的使用

if语句是条件判断语句,if语句的语法与while相似
if (test-condition)
    statement
即:如果测试条件(test-condition)为true,则执行statement语句
这里的statement语句既可以是一条语句,也可以使多条语句组成的语句块。
但是这里必须注意:如果是多条语句,必须用大括号括起来。
否则就只会执行if语句下紧跟着的一句,而不会执行多余的语句。
当然为了养成良好的编码习惯,我们经常要求即使if下面只有条语句,我们也要使用大括号括起来。

if语句的几种常见的用法:

1. if语句单独使用

2. if ... else配合使用

3. if ... else if ... else配合使用

源码:

// Len_ifelse.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{

	char data[5] = { "abcd" };
	// 1. if单独使用
	printf("\n\n1. if单独使用\n");
	for (int t = 0; t < strlen(data); t++)
	{
		if (data[t] == 'c')
		{
			printf("\t I find the c\n");
		}
	}

	// 2. if...else配合使用
	printf("\n\n2. if...else配合使用\n");
	for (int t = 0; t < strlen(data); t++)
	{
		if (data[t] == 'c')
		{
			printf("\t I find the c\n");
		}
		else
		{
			printf("\t The data is:%c\n", data[t]);
		}
	}

	// 3. if...else if... else配合使用
	printf("\n\n3. if...else if...else配合用\n");
	for (int t = 0; t < strlen(data); t++)
	{
		if (data[t] == 'c')
		{
			printf("\t I find the c\n");
		}
		else if (data[t] == 'a')
		{
			printf("\t I find the a\n");
		}
		else 
		{
			printf("\t The data is:%c\n", data[t]);
		}
	}

	return 0;
}

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WendyWJGu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值