C++学习笔记(二) if语句

本文详细介绍了C++中if语句的三种形式及其使用场景,包括缺省形式、完整形式和并列形式,并通过实例展示了如何应用这些形式来解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++学习笔记(二)  if语句


   if条件语句有三种形式:

     1.一般(缺省)形式  if(bool) 语句

#include<iostream>
using namespace std;

void main()
{
	int price = 12;//定义快餐的价格为12
	int money = 0;
	cout << "快餐价格为12元,请付钱:" << endl;
	cin >> money;

	if (money >= price)
		cout << "有足够的钱购买快餐" << endl;
        system("pause");
}


    2.完整形式  if(bool) {语句1} else {语句2}

#include<iostream>
using namespace std;

void main()
{
	int price = 12;//定义快餐的价格为12
	int money = 0;
	cout << "快餐价格为12元,请付钱:" << endl;
	cin >> money;

	if (money >= price)
	{
		int residue = money - price;//剩余的钱
		cout << "获得一份快餐,剩余:" << residue << "元" << endl;
	}
	else
	{
		cout << "钱不够- -" << endl;
	}
       system("pause")
}


     3.并列形式  if(bool){语句1}  else if(bool){语句2} ....else{语句n}

#include<iostream>
using namespace std;

void main()
{
	int price_a = 12;//定义快餐A的价格为12
	int price_b = 22;//定义快餐A的价格为22
	int money = 0;
	cout << "快餐A价格为12元,快餐B价格为22元,请付钱:" << endl;
	cin >> money;

	if (money >= price_a + price_b)
	{
		int residue = money - price_a - price_b;
		cout << "获得一份A快餐和一份B快餐,剩余:" << residue << "元" << endl;
	}
	else if (money >= price_b)
	{
		int residue = money - price_b;
		cout << "获得一份B快餐,剩余:" << residue << "元" << endl;
	}
	else if (money >= price_a)
	{
		int residue = money - price_a;
		cout << "获得一份A快餐,剩余:" << residue << "元" << endl;
	}
	else
	{
		cout << "钱不够- -" << endl;
	}
       system("pause");
}


        if语句嵌套if语句

#include<iostream>
using namespace std;

void main()
{
	int bicycle = 230;
	int umbrella = 35;
	int pen = 10;
	int money = 0;
	char selecte = 0;

	cout << "商城大甩卖:" << endl;
	cout << "自行车230元,雨伞35元,钢笔10元。" << endl;

	cout << "请付钱:" << endl;
	cin >> money;
	cout << "请选择您需要的商品:a为自行车,b为雨伞,c为钢笔" << endl;
	cin >> selecte;

	if (selecte = 'a')
	{
		if (money >= bicycle)
		{
			int residue = money - bicycle;
			cout << "您已成功购买自行车,剩余:" << residue << "元" << endl;
		}
		else
		{
			cout << "金钱不够,请充值" << endl;
		}
	}
	else if (selecte = 'b')
	{
		if (money >= umbrella)
		{
			int residue = money - umbrella;
			cout << "您已成功购买雨伞,剩余:" << residue << "元" << endl;
		}
		else
		{
			cout << "金钱不够,请充值" << endl;
		}
	}
	else if (selecte = 'c')
	{
		if (money >= pen)
		{
			int residue = money - pen;
			cout << "您已成功购买钢笔,剩余:" << residue << "元" << endl;
		}
		else
		{
			cout << "金钱不够,请充值" << endl;
		}
	}
	else
	{
		cout << "请输入正确编号" << endl;
	}
       system("pause");
}



        注意:如果省去{} 只能关联一行代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值