C语言求 ②某商场给出的购物折扣率如下: 购物金额<100元,不打折; 100元≦购物金额<30

C语言求 ②某商场给出的购物折扣率如下:

购物金额<100元,不打折;
100元≦购物金额<300元,9折;
300元≦购物金额<500元,8折;
购物金额≧500元,7.5折。
输入购物金额,输出折扣率和购物实际付款额。(要求分别使用if ……else if语句和switch语句两种方法编程。)

#include <stdio.h>
int main(void)
{ float cost;
float discount,pay;
printf("请输入购物金额:");
scanf("%f",&cost);
if(cost>=0)//购物金额大于等于0
{

if(cost>=0&&cost<100)//购物金额为小于100
discount=1;
else if(cost>=100&&cost<300)//购物金额大于等于100小于300
discount=0.9;
else if(cost>=300&&cost<500)//购物金额大于等于300小于500
discount=0.8;
else //购物金额大于等于500
discount=0.75;

pay=cost*discount;
printf("当购物金额是%.2f,折扣为%.2f,实际付款%.2f\n",cost,discount,pay);
/**************************switch语句实现****************************************/
printf("使用switch语句:\n");
int num=cost/100;//对cost/100取整(例如cost=150,num=1)确定所在的区间范围
switch(num){
case 0: discount=1;break;//购物金额为小于100
case 1: discount=0.9;break;
case 2: discount=0.9;break;//case 1,2为购物金额大于等于100小于300
case 3: discount=0.8;break;
case 4: discount=0.8;break;//case 3,4为购物金额大于等于300小于500
default: //购物金额大于等于00
discount=0.75;break;}
pay=cost*discount;
printf("当购物金额是%.2f,折扣为%.2f,实际付款%.2f\n",cost,discount,pay);}
else //购物金额小于0
printf("输入有误,cost必须满足大于等于0");
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-05-28

只会用switch,不好意思

#include <stdio.h>

int main()

{

int c,d;

float w,p;

printf("Input payment:");

scanf("%f",&p);

if(p>=1000)c=10;

else c=p/100;

switch(c)

{

case 0:

d=0;

break;

case 1:

d=5;

break;

case 2:

case 3:

case 4:

d=8;

break;

case 5:

case 6:

case 7:

case 8:

case 9:

d=10;

break;

case 10:

d=15;

break;

default:

printf("error");

break;

}

w=p*(1-d/100.0);

printf("price = %.1f\n",w);

return 0;

}

第2个回答  2015-05-12
vc6.0各codeblocks两个编译器均可通过,我把两个方法合成在一个程序中了,请楼主细细体会里面的细节,初学都要慢慢的养成好习惯,还有,上班偷偷敲代码不容易,楼主采纳一下呗

#include <stdio.h>
#include <stdlib.h>
int main()
{
//购物金额<100元,不打折;
//100元≦购物金额<300元,9折;
//300元≦购物金额<500元,8折;
//购物金额≧500元,7.5折。
//输入购物金额,输出折扣率和购物实际付款额。(要求分别使用if ……else if语句和switch语句两种方法编程。)

float total = 0;
printf("请输入购物金额:");
scanf("%f",&total);

if(total > 0)
{

/**************************if else语句实现****************************************/
if(total<100)
{
printf("吝啬鬼,花这么少钱,没折打,折扣是0,实际付款是:%.2f\n",total);
}
else if(total>=100 && total < 300)
{
printf("折扣是9折,实际付款是:%.2f\n",total*0.9);
}
else if(total>=300 && total < 500)
{
printf("折扣是8折,实际付款是:%.2f\n",total*0.8);
}
else
{
printf("折扣是7.5折,实际付款是:%.2f,土豪,我们做基友吧\n",total*0.75);
}

/**************************switch语句实现****************************************/
//switch语句实现
printf("\n下面是用switch语句实现:\n");

//请楼主理解这句
int Switch_num = total / 100;//这里是关键,把这个轮换成常量的表达式case才能执行

switch(Switch_num)
{
case 0:
printf("吝啬鬼,花这么少钱,没折打,折扣是0,实际付款是:%.2f\n",total);
break;

case 1:
printf("折扣是9折,实际付款是:%.2f\n",total*0.9);
break;
case 2:
printf("折扣是8折,实际付款是:%.2f\n",total*0.8);
break;
default:
printf("折扣是7.5折,实际付款是:%.2f,土豪,我们做基友吧\n",total*0.75);
break;
}

}
else
{
printf("金额必须是大于0!\n");
}

return 0;
}追问

非常给力的搞笑,谢谢咯。初学没办法,女孩子学这方面没兴趣,碍于是作业。

本回答被提问者采纳