3.1.1if语句 if语句中,如果内嵌语句又是i语句,就构成了嵌套i语句。i语句 可实现二选一,而嵌套i语句则可以实现多选一的情况。嵌套有两种 形式,一种是嵌套在else分支中,格式为: if(<表达式1>)<语句1>; else if(<表达式2>)语句2; else if else<语句n>; 第二种是嵌套在if分支中,格式为: if(<表达式1>)if(<表达式2>)<语句1>; else<语句2> 岗心國
3.1.1 if 语句 if 语句中,如果内嵌语句又是if语句,就构成了嵌套if语句。if语句 可实现二选一,而嵌套if语句则可以实现多选一的情况。嵌套有两种 形式,一种是嵌套在else分支中,格式为: if (<表达式1>) <语句1>; else if (<表达式2>)语句2; else if … else <语句n>; 第二种是嵌套在if分支中,格式为: if (<表达式1>)if (<表达式2>) <语句1>; else<语句2>;
3.1.1if语句 【例3.3】用嵌套语句完成【例3.2】的任务。 方法1:采用第二种嵌套形式 ∥文件名:Ex331cpp 输入三个整数 #include <iostream.h> 10823 void main(t a=10b=8c=23 int a. b. c. max: a>b a<c max=c cou<<"输入三个正数:"; cin>>a>>b>>c; 输出最大数为:max=23 cout<<"a="<<a<<"t"<<"b="<<b<<"lt"<<"c="<<c<<endl; if(a>b) if(a>c)max=a; 1a>b且a>c else max=c: ∥a>b且 /a<=b if(b>c) max=b //b>=a且b>c else max=c, /hb>=a且b<c 岗心國 cout<<"最大数为max="<<max<<endl;}
3.1.1 if 语句 【例3.3】用嵌套if语句完成【例3.2】的任务。 //方法1:采用第二种嵌套形式 //文件名:Ex3_31.cpp #include <iostream.h> void main(){ int a, b, c, max; cout<<"输入三个正数:"; cin>>a>>b>>c; cout<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<endl; if(a>b) if(a>c) max=a; //a>b且a>c else max=c; //a>b且a<c else //a<=b if(b>c) max=b; //b>=a且b>c else max=c; //b>=a且b<c cout<<"最大数为:max="<<max<<endl;} 输入三个整数 10 8 23 a=10 b=8 c=23 a>b a<c max=c 输出 最大数为:max=23
3.1.1if语句 方法2:采用第一种嵌套形式 输入三个整数 ∥文件名Ex332cpp 10823 #include <iostream.h> a=10b=8c=23 void main(t Int a, b, c, max; a>b a<c max=c cou<"输入三个正数 r:"!s 输出最大数为:max=23 cin>>a>>b>>c: cout<<"a="<<a<<"lt"<<"b="<<b<<"t'<<"e="<c<<endl; if(a>b&&a>c)max=a; else if(b>a&&b>c) max=b else max=c: cout<"最大数为:max=<<max<<endi;} 岗心國
3.1.1 if 语句 //方法2:采用第一种嵌套形式 //文件名:Ex3_32.cpp #include <iostream.h> void main(){ int a,b,c,max; cout<<"输入三个正数:"; cin>>a>>b>>c; cout<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<endl; if(a>b&&a>c) max=a; else if(b>a&&b>c) max=b; else max=c; cout<<"最大数为:max="<<max<<endl; } 输入三个整数 10 8 23 a=10 b=8 c=23 a>b a<c max=c 输出 最大数为:max=23
3.1.1if语句 例3.4】某商场优活动规定,某种商品单 价为80元,一次购买5件以上(包含 5件)10件以下(不包含10件)打9 折,一次购买10件以上(包含10件) 打8折。设计程序根据户的购买量计 算总价。 岗心國
3.1.1 if 语句 【例3.4】 某商场优惠活动规定,某种商品单 价为80元,一次购买5件以上(包含 5件)10件以下(不包含10件)打9 折,一次购买10件以上(包含10件) 打8折。设计程序根据客户的购买量计 算总价
3.1.1if语句 ∥文件名:Ex34cpp #include <iostream. h> 输入购买件数 void main(t count 13 float price=80, discount, amount;/单价、折扣、总价 count<5 discount=1 int count /购买件数 cout<"输入购买件数:"<<end; amount=80*3*1=240 cin>>count 输出购买件数3 if(count<5) discount=1: 单价:80折扣:1 总价:240 else if(count<10) discount=0.9; else discount=0.8; amount=price*count*discount cout<<"购买件数:"<< count<endl cout"单价:"<pie<"折扣:"<ds d: cout<"总价:"<< amounts<endl;} 岗心國
3.1.1 if 语句 //文件名:Ex3_4.cpp #include <iostream.h> void main(){ float price=80,discount,amount;//单价、折扣、总价 int count; //购买件数 cout<<"输入购买件数:"<<endl; cin>>count; if(count<5) discount=1; else if(count<10) discount=0.9; else discount=0.8; amount=price*count*discount; cout<<"购买件数:"<<count<<endl; cout<<"单价:"<<price<<'\t'<<"折扣:"<<discount<<endl; cout<<"总价:"<<amount<<endl; } 输入购买件数 count=3 count<5 discount=1 amount=80*3*1=240 输出 购买件数:3 单价:80 折扣:1 总价:240