算法 1、输入每吨运费ρ、货物重量w、运输里程s; 2、根据运输里程s计算折扣d; 3、计算总运费f=p*W*s*(1-d); 4、输出计算结果; 算法细化:2、根据运输里程s计算折扣d 分析: 如果用 switch语句,必须使表达式符合语法要 求,分析发现,里程s的分段点均是250的倍数, 因此,将里程s除以250,取整数商,便得到若 0k干整数值
ok 算法 1、输入每吨运费p、货物重量w、运输里程s; 2、根据运输里程s计算折扣d; 3、计算总运费f=p*w*s*(1-d); 4、输出计算结果; 算法细化: 2、根据运输里程s计算折扣d 分析: 如果用switch语句,必须使表达式符合语法要 求,分析发现,里程s的分段点均是250的倍数, 因此,将里程s除以250,取整数商,便得到若 ok 干整数值
switch(c=s/250)i s<250不打折扣 case 0: d=0; break; 250<=s<5002号折扣 case 1: d=0. 02: break 500<=s<1000 case 2 5号折扣 case 3: d=0.05: break 1000<=s<2000 case 4 8号折扣 case 5 case 6 case 7: d=0.08 break 2000<=s<3000 case 8 108折扣 case 9 case 10: case 11: d=0.1 break 3000<=815号折扣 default: d=0.15 k
ok switch(c=s/250) { case 0: d=0; break; case 1: d=0.02; break; case 2: case 3: d=0.05; break; case 4: case 5: case 6: case 7: d=0.08; break; case 8: case 9: case 10: case 11:d=0.1;break; default:d=0.15; } s<250 不打折扣 250<=s<500 2%折扣 500<=s<1000 5%折扣 1000<=s<2000 8%折扣 2000<=s<3000 10%折扣 3000<=s 15%折扣
include <iostream.h> include <iomanip.h> void main() int c,s, float p, w,d,fi cout<<"输入运输单价p,重量w和里程s:"<<endL; cin>>p>>w>>s;c=s/250; switch(c)i case 0: d=0: break case 1:d=0.02: break case 2: case 3: d=0.05: break i case 4: case 5: case 6: case 7:d=0.08 break i case 8: case9: casel0: casel1:d=0.1: break default:d=0.15 f中*w*s*(1-d); cout<<"单价为"<<p<\t"<<"重量为"<<w<\t <<里程为"<<s<end1; ok cout<<"折扣为"<<d<end1<<"运费为"<<f<<end1;} 请在VC++平台上运行,输入不同的里程,使程序所有分支都可以被执行一次
ok #include <iostream.h> #include <iomanip.h> void main( ) { int c,s; float p,w,d,f; cout<<"输入运输单价p,重量w和里程s:"<<endl; cin>>p>>w>>s; c=s/250; switch(c){ case 0:d=0;break; case 1:d=0.02;break; case 2:case 3:d=0.05;break; case 4:case 5:case 6:case 7:d=0.08; break; case 8:case9:case10:case11:d=0.1;break; default:d=0.15; } f=p*w*s*(1-d); cout<<"单价为"<<p<<'\t'<<"重量为"<<w<<'\t‘ <<"里程为"<<s<<endl; cout<<"折扣为"<<d<<endl<<"运费为"<<f<<endl;} 请在VC++平台上运行,输入不同的里程,使程序所有分支都可以被执行一次。 ok
【例3.7】设计一个计算器程序,实现加、减、乘、除运算。 #include <iostream.h> void main() float numl, num2 result char op; cout<<"输入操作数1,运算符,操作数2:"<<end1; cin>>num1>>op>>num2 i switch(op)t case + result numl+num2; break i case result numl-num2: break case i*i: result num1*num2: break case '/i: result num1/num2; break i default:cout<<op<<"是无效运算符!; if(op op==-′||。p== cout<<numl<<op<<num2<<=l<<result<<endl k 常量表达式采用字符型,上机运行一下
ok 【例3.7】 设计一个计算器程序,实现加、减、乘、除运算。 #include <iostream.h> void main( ) { float num1,num2,result; char op; cout<<"输入操作数1,运算符,操作数2:"<<endl; cin>>num1>>op>>num2; switch(op){ case '+': result = num1+num2; break; case ‘-': result = num1-num2; break; case ‘*': result = num1*num2; break; case ‘/': result = num1/num2; break; default : cout<<op<<“是无效运算符!”; } if(op==‘+’||op==‘-’||op==‘*’||op==‘/’) cout<<num1<<op<<num2<<"="<<result<<endl; } 常量表达式采用字符型,上机运行一下
3.2循环结构程序设计 循环控制语句是三种基本流程控制语句之 C++提供以下三种循环语句: While语句 do-whi1e语句 f。r语句
ok 循环控制语句是三种基本流程控制语句之 一。C++提供以下三种循环语句: ▪ while语句 ▪ do-while 语句 ▪ for语句 3.2 循环结构程序设计