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");
}