程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。
#include<stdio.h>
int main()
{
double i;
double bonus1,bonus2,bonus4,bonus6,bonus10,bonus;
printf("你的净利润是:\n");
scanf("%lf",&i);
bonus1=100000*0.1;
bonus2=bonus1+100000*0.075;
bonus4=bonus2+200000*0.05;
bonus6=bonus4+200000*0.03;
bonus10=bonus6+400000*0.015;
if(i<=100000) {
bonus=i*0.1;
} else if(i<=200000) {
bonus=bonus1+(i-100000)*0.075;
} else if(i<=400000) {
bonus=bonus2+(i-200000)*0.05;
} else if(i<=600000) {
bonus=bonus4+(i-400000)*0.03;
} else if(i<=1000000) {
bonus=bonus6+(i-600000)*0.015;
} else if(i>1000000) {
bonus=bonus10+(i-1000000)*0.01;
}
printf("提成为:bonus=%lf",bonus);
printf("\n");
}
优化如下:
#include <stdio.h>
#define WAN 10000
int main()
{
double I = 0; // 利润
double B = 0; // 奖金
scanf("%lf", &I);
I /= WAN;
if (I > 100 * WAN)
{
B += ((I - 100) * 0.01);
I = 100;
}
if (I > 60)
{
B += ((I - 60) * 0.015);
I = 60;
}
if (I > 40)
{
B += ((I - 40) * 0.03);
I = 40;
}
if (I > 20)
{
B += ((I - 20) * 0.05);
I = 20;
}
if (I > 10)
{
B += ((I - 10) * 0.075);
I = 10;
}
B += (I * 0.1);
printf("%lf", B);
}
使用循环优化代码的适用性:
#include<stdio.h>
int main()
{
int i;
double lirun;
double jiangjin = 0;
float fanwei[] = {100000, 200000, 400000, 600000, 1000000};
float ticheng[] = {0.1, 0.075, 0.05, 0.03, 0.015, 0.01};
printf("您好,请问您的净利润是多少?\n");
scanf("%lf", &lirun);
for (i=0;i<5;i++)
{
if (lirun < fanwei[i])
{
jiangjin += lirun * ticheng[i];
break;
}
else
{
jiangjin += fanwei[i] * ticheng[i];
lirun -= fanwei[i];
}
}
printf("奖金是%.2lf\n", jiangjin);
return 0;
}
利用 switch 的击穿现象
#include <stdio.h>
int main(){
double d;
int money = 100000;
float res=0.0;
int flag;
scanf("%lf",&d);
flag = (int)(d/money);
flag = flag >10?10:flag;
switch(flag){
case 10:
res += (d-10*money)*0.01;
d = 10*money;
case 9:
case 8:
case 7:
case 6:
res += (d-6*money)*0.015;
d = 6*money;
case 5:
case 4:
res+= (d-4*money)*0.03;
d = 4*money;
case 3:
case 2:
res += (d-2*money)*0.05;
d = 2*money;
case 1:
res += (d-money)*0.075;
d = money;
case 0:
res += d *0.1;
}
printf("%.2f\n",res);
return 0;
}
登录后提交答案
暂无评论,来抢沙发