我想问一下各位同学!不才写的这个程序怎么样才可以简短呢!我好像不会简短写
各位同学晚上好!刚刚下班回家思考了一下,打出switch语句的运费问题我想请教一下各位同学,我打得这个switch语句能不能再简短点呢?我感
觉我写的语句都很复杂!
一下是不才的我写的程序:
#include <stdio.h>
void main()
{
double p,w,s,f;
printf("Please input three number from keyboard:\n");
scanf("%lf%lf%lf",&p,&w,&s);
switch(s<250?1:0)
{
case 1:
{
f=p*w*s;
printf("%lf",f);
break;
}
case 0:
{
switch(s<500?3:2)
{
case 3:
{
f=p*w*s*0.98;
printf("%lf",f);
break;
}
case 2:
{
switch(s<1000?5:4)
{
case 5:
{
f=p*w*s*0.95;
printf("%lf",f);
break;
}
case 4:
{
switch(s<2000?7:6)
{
case 7:
{
f=p*w*s*0.92;
printf("%lf",f);
break;
}
case 6:
{
switch(s<3000?9:8)
{
case 9:
{
f=p*w*s*0.90;
printf("%lf",f);
break;
}
case 8:
{
f=p*w*s*0.85;
printf("%lf",f);
break;
}
}
}
}
}
}
}
}
}
}
} 能用if的你用switch。没必要吧。
看这代码,用别的简短多了。你还是把题目写出来吧。看你这代码就纠结 本帖最后由 Croper 于 2019-5-14 20:06 编辑
正常来说这种分段的都不会用switch的,
非要用switch也会先计算个index再switch,
用数组不管是代码的简洁程度还是修改代码的难易程度都好多了#include <stdio.h>
void main()
{
const int seg[]={250,500,1000,2000,3000};
const double fac[]={1,0.98,0.95,0.92,0.9,0.85};
double p,w,s,f;
printf("Please input three number from keyboard:\n");
scanf("%lf%lf%lf",&p,&w,&s);
int i;
for (i=0;i<5;++i){
if (s<seg) break;
}
f=p*w*s*fac;
printf("%lf",f);
}
本帖最后由 BFSDT 于 2019-5-14 23:36 编辑
double p, w, s, f;
scanf("%lf%lf%lf", &p, &w, &s);
switch ((long)s/250){
case 0:
f = p * w * s;
break;
case 1:f = p * w * s * 0.98;
break;
case 2:
case 3:
f = p * w * s * 0.95;
break;
case 4:
case 5:
case 6:
case 7:
f = p * w * s * 0.92;
break;
case 8:
case 9:
case 10:
case 11:
f = p * w * s * 0.90;
break;
default:
f = p * w * s * 0.85;
}
printf("%lf", f);
return 0;
页:
[1]