天气: 阴雨
心情: 平静
今天我们以几个简单的例子来完成对if-else 和 switch-case的学习
1、计算工人工资
已知某公司员工的底薪为500元,员工所销售的软件金额与提成数如下:
销售额<=2000 没有提成
2000<销售额<=5000 提成8%
5000<销售额<=10000 提成10%
销售额>=10000 提成12%
我们完全可以用if -else来做这道题,但是为了增加难度,建议用switch,本题的关键就是销售额的取整问题
我们用基数1000来确定提成的值。
#include<stdio.h>
void main()
{
float salary=500;
int k;
int profit;
printf("please input the profit of this month: ");
scanf("%d",&profit);
if(profit%1000==0)
k=profit/1000;
else
k=profit/1000+1;
switch(k)
{
case 0:
case 1:
case 2:break;
case 3:
case 4:
case 5:
salary+=profit*0.08;
break;
case 6:
case 7:
case 8:
case 9:
case 10:
salary+=profit*0.1;
break;
default:
salary+=profit*0.12;
break;
}
printf("the salary of this month is: %5.2f\n",salary);
}
我们需要注意的俩个问题:
1)switch中的每个case后面一定要有break,否则程序会一个case一个case的执行!
2)数据的格式化输出5.2%的意思是数据长度5位(这个其实不一定的,看数据了),精度为小数点后保留两位
2、判断闰年
代码我就不写了,但是有一个扩展:万年历的实现,格式自己定义。
提示:注意闰年情况,判断某一天是星期几,已知1900年的1月1日是星期一。
源代码见附件,并非本人作品..
3、阶梯数问题
阶梯数在密码学中有应用,具体的我也不清楚,只是最近上密码学的课老师有讲到。
eg:在你的面前有一条长长的梯子,如果你每步跨俩阶,那么最后剩一阶,如果你每步跨三阶,那么最后剩俩阶
如果你每步跨五阶,那么最后剩四阶,如果你每步跨六阶,那么最后剩五阶,只有你每步跨七阶的时候,最后才
正好走完。请问这条梯子至少有多少阶(求三位阶梯数)。
#include<stdio.h>
void main()
{
int i;
for(i=100;i<1000;i++)
{
if(i%2==1&&i%3==2&&i%5==4&&i%6==5&&i%7==0)
printf("the number of stairs is %d\n",i);
}
}
4、自动售货机
今天,我们再一次以一条娱乐性的程序结尾。
#include<stdio.h>
#include <stdlib.h>
void main()
{
int button;
system("clr");
printf("*******************************\n");
printf("* the button you can chose: *\n");
printf("* 1. Chocolate *\n");
printf("* 2. Cake *\n");
printf("* 3. Coca-Cola *\n");
printf("*******************************\n\n");
printf("chose the button from 1~3:\n");
scanf("%d",&button);
switch(button)
{
case 1:
printf("you chose the chocolate.\n");
break;
case 2:
printf("you chose the cake.\n");
break;
case 3:
printf("you chose the coca-cola.\n");
break;
default:
printf("\nError!\n");
break;
}
printf("\n");
}
学习语言是一个细致活,不能心急,一点一点的渗透,周末愉快!