- 对switch语句的举例
//The first project
/*******************************************************************
题意:某员工底薪800,所接工程利润profit(整数)与提成的关系如下,
试计算当月薪水.
********************************************************************/
#include<stdio.h>
void main()
{
int a; //a代表一等级,表示不同分级下的利润加成
long profits;
float n,salary=800;
/*注意:在设不同类型的变量后,涉及变量的基本运算,这时会有强制类型转换。*/
printf("The profits is: ");
scanf("%d",&profits);
a=(profits-1)/1000;
switch(a)
{
case 0: n=0;break;
case 1: n=0.10;break;
case 2:
case 3:
case 4: n=0.15;break; //switch选择中,只有运算遇到break才会停止,即跳出循环。
case 5:
case 6:
case 7:
case 8:
case 9: n=0.20;break;
default: n=0.25;break;
}
printf("The salary is=%.2f\n",salary+profits*n);
}
2.
//The second project
/*******************************************************************
从键盘上输入任意两个数和运算符( + - * /),然后算出它们的值。
********************************************************************/
#include<stdio.h>
void main()
{
float a,b,c;
char ch;
printf("The number to be calculated is:");
scanf("%f%f",&a,&b);
fflush(stdin);
/****清键盘缓冲区。scanf首先将输入文本放在内部的一个缓冲区(即键盘缓冲区)中,然后将缓冲区的文本按照第一个参数的格式控制符转换成各种类型的数据。当用户输入文本过长,这些文本放在缓冲区中由scanf依次调用,从而影响后面的scanf函数。****/
printf("The arithmetic lable is:");
scanf("%c",&ch);
switch(ch)
{
case '+': c=a+b;printf("The result is=%.2f\n",c);break;
case '-': c=a-b;printf("The result is=%.2f\n",c);break;
case '*': c=a*b;printf("The result is=%.2f\n",c);break;
case '/': if(!b)
printf("calculation error!");
else
c=a/b;printf("The result is=%.2f\n",c);
break;
default :
printf("calculation can not be allowed!");break;
}
}
3.
//The third project
/*******************************************************************
从键盘上输入任意两个整数,统计两个数之间的0,1...9的个数。
eg:给出101,105.则0有5个,1有6个,2,3,4,5各有1个。
********************************************************************/
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a,b,c[10]={0},m,n,i;
//对数组进行初始化,数组中的各个元素为0
printf("The numbers is:");
scanf("%d%d",&a,&b);
if(a>b||a<0||b<0)
{
printf("input error!\n");
exit(-1);
}
//输入检验
else
{
for(;a<=b;a++)
{
m=a; //m代表商,n代表余数。通过一步步运算在m不为0的情况下来判断余数是否为0,来对数组中的元素进行赋值操作
while(m)
{
n=m%10;
switch(n)
{
case 0: c[0]++;break;
case 1: c[1]++;break;
case 2: c[2]++;break;
case 3: c[3]++;break;
case 4: c[4]++;break;
case 5: c[5]++;break;
case 6: c[6]++;break;
case 7: c[7]++;break;
case 8: c[8]++;break;
case 9: c[9]++;break;
default: ;break;
}
m/=10;
}
}
for(i=0;i<10;i++)
printf("%d(%d)\t\n",i,c[i]); //()只是表示输出项,便于观察
}
}
4.
//---- ADDED
/*******************************************************************
简单栗子:任意输入一个数,求它是几位数
********************************************************************/
#include<stdio.h>
int main()
{
int n,i=0;
printf("input a number:");
scanf("%d",&n);
while(n)
{
n/=10;
i++;
}
printf("该数的位数是:%d\n",i);
return 0;
}