c语言基础,求教大神!!!
已注解,已测试。
#include <stdio.h>
float discount_rate,acost; //因为子函数中需要使用,所以定义成全局变量
void if_dr_ac(float c)
{
if(c >= 1000) //用级联式if else给折扣率赋值
discount_rate = 0.8;
else if(c >= 500)
discount_rate = 0.85;
else if(c >= 200)
discount_rate = 0.9;
else if(c >= 100)
discount_rate = 0.95;
else
discount_rate = 1;
acost = c*discount_rate; //计算实际花费
printf("%f\t%f\n",discount_rate,acost); //按照主函数中格式输出结果
}
void switch_dr_ac(float c)
{
int n;
n = (int)c/100; //去掉价格的后2位,转换成整型
discount_rate = 0.8; //配合下面的 += 0.05
switch(n)
{
case 0:discount_rate += 0.05;//这样就可以不用写break了,怎么样,人才吧~
case 1:discount_rate += 0.05;
case 2:
case 3:
case 4:discount_rate += 0.05;
case 5:
case 6:
case 7:
case 8:
case 9:discount_rate += 0.05;
default:break;
}
acost = c*discount_rate;
printf("%f\t%f\n",discount_rate,acost);
}
int main(void)
{
float cost;
bed: printf("Please input the price of the goods:");
scanf("%f",&cost);
if(cost < 0) //这样符合实际一点
{
printf("Illegal input!");
goto bed;
}
printf("Discount rate:\tActual cost:\n"); //输出格式
//if_dr_ac(cost); //想用哪个语句实现就去掉哪个的注释
//switch_dr_ac(cost);
return 0;
}
if操作更加简单,我相信你可以自己写,if elseif一直用就好。
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a;
float p = 0;
float b = 0.0;
printf("输入消费金额:\n");
scanf_s("%d", &a, 4);
switch (a/100)
{
case 0:
break;
case 1:
p = 0.05;
break;
case 2:
case 3:
case 4:
p = 0.1;
break;
case 5:
case 6:
case 7:
case 8:
case 9:
p = 0.15;
break;
default:
p = 0.2;
break;
}
b = a*(1 - p);
printf_s("折扣率为:%f\n实付金额为:%f\n", p, b, 3, 3);
system("pause");
}
#include<stdio.h>
void main()
{
float sum,f;
int case_i;
printf("请输入您的消费金额:");
scanf("%f",&sum);
if(sum<100)
case_i=1;
else if(sum<200)
case_i=2;
else if(sum<500)
case_i=3;
else if(sum<1000)
case_i=4;
else
case_i=5;
switch(case_i)
{
case 1:f=sum;
printf("您的折扣率为:0%%\n实付金额为:%.2f\n",f);
break;
case 2:f=sum*0.95;
printf("您的折扣率为:5%%\n实付金额为:%.2f\n",f);
break;
case 3:f=sum*0.9;
printf("您的折扣率为:10%%\n实付金额为:%.2f\n",f);
break;
case 4:f=sum*0.85;
printf("您的折扣率为:15%%\n实付金额为:%.2f\n",f);
break;
case 5:f=sum*0.8;
printf("您的折扣率为:20%%\n实付金额为:%.2f\n",f);
break;
}
}
//感觉用了switch就变得特别麻烦,如果不是特别要求,不建议用switch,用数组加for就可以解决