C语言及程序设计初步例程-26 利用switch语句解决问题

来源:互联网 发布:豆瓣fm for windows 编辑:程序博客网 时间:2024/06/01 15:30

贺老师教学链接  C语言及程序设计初步 本课讲解


应用:计算运费
每公里每吨货物的基本运费为p(price),货物重为w(weight),距离为s,折扣为d(discount),则总运费f(freight)的计算公式为 freight=price*weight*s*(1-discount)

#include <stdio.h>int main(){    int c,s;    float p,w,d,f;    printf("please enter p,w,s: ");    scanf("%f%f%d", &p, &w, &s);    if(s>=3000)        c=12;    else        c=s/250;    switch (c)    {    case 0:        d=0;break;    case 1:        d=2;break;    case 2:    case 3:        d=5;break;    case 4:    case 5:    case 6:    case 7:        d=8;break;    case 8:    case 9:    case 10:    case 11:        d=10;break;    case 12:        d=15;break;    }    f=p*w*s*(1-d/100.0);    printf("freight=%.2f\n", f);    return 0;}

用switch求分段函数
#include <stdio.h>#include <math.h>int main(){    double x, y;    int t;    scanf("%lf", &x);    t=(x<2)+(x<6)+(x<10);    switch(t)    {    case 3: //(x<2)、(x<6)、(x<10)全为真时        y=x;        break;    case 2://(x<6)、(x<10)为真时        y=x*x+1;        break;    case 1://仅(x<10)为真时        y=sqrt(x+1);        break;    case 0:  //(x<2)、(x<6)、(x<10)没有一个为真,即x>=10        y=1/(x+1);    }    printf("%lf\n", y);    return 0;}


0 0
原创粉丝点击