基础C语言代码练习
C语言代码练习Day01
1.促销计算
题目: 某百货公司为了促销,采用购物打折的优惠方法,每位顾客一次购物:在 1000 元以上者,按
9.5 折优惠;在 2000 以上者,按 9 折优惠;在 3000 以上者,按 8.5 折优惠;在 5000 以上者,
按 8 折优惠;编写程序,购物款数,计算并输出优惠价。
题目解析: 根据题意判断输入金额达到哪一打折区间,然后进行打折优惠计算。
#include <stdio.h>
int main(){
double money;
scanf("%lf",&money); //输入购物金额
if (money < 1000) printf("discount=1,pay=%.2lf",money); //直接输出金额,结果保留两位小数
if (money > 1000 && money < 2000) printf("discount=0.95,pay=%.2lf",money*0.95); //将金额乘以折扣,结果保留两位小数
if (money > 2000 && money < 3000) printf("discount=0.9,pay=%.2lf",money*0.9);
if (money > 3000 && money < 5000) printf("discount=0.85,pay=%.2lf",money*0.85);
if (money > 5000) printf("discount=0.8,pay=%.2lf",money*0.8);
return 0;
}
2.反序数
题目: 将输入的正整数顺序颠倒并输出,例如输入一个整数为123,将其转换为反序之后的整数321。
题目解析: 运用while循环将输入的整数从最低位数开始,在增加位数后加上更高一位的数。
#include<stdio.h>
int main(){
int n;
int ans = 0; //ans用来记录反转后的数
scanf("%d",&n);
while (n > 0) {
ans *= 10; //提升一个位数
ans +=n%10; //加上n的最低位
n /=10; //去掉n的最低位并下降一个位数
}
printf("反转后的整数为%d",ans);
return 0;
}
949

被折叠的 条评论
为什么被折叠?



