c语言分段函数 switch语句

img


c语言编程-分段函数
用switch 语句编程求分段函数的值,已知a=2,b=3

x - 0.5 取整数得到0 1 2 3的整数就可以用case 0: case 1: case 2: case 3:控制分段了

#include <stdio.h>
int main()
{
    double x, y, a = 2, b = 3;
    scanf("%lf", &x);
    int n = (int)(x - 0.5);
    switch (n)
    {
    case 0:
        y = a + b * x;
        break;
    case 1:
        y = a - b * x;
        break;
    case 2:
        y = a * b * x;
        break;
    case 3:
        y = a / (b * x);
        break;
    }
    printf("%lf", y);
    return 0;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

用swtich(x*2)进行判断

#include <stdio.h>
int main()
{
    double x,y,a=2,b=3;
    int d;
    scanf("%lf",&x);
    d = (int)(x*2+0.01);
    switch(d)
    {
        case 1:
        case 2:
          d = a+b*x;
          break;
        case 3:
        case 4:
          d = a - b*x;
          break;
        case 5:
        case 6:
          d = a*b*x;
          break;
        case 7:
        case 8:
          d = a/(b*x);
          break;
    }
    printf("%lf",d);
    return 0;
}