鱼C论坛

 找回密码
 立即注册
查看: 3150|回复: 3

【在线等】分别用switch和if 求分段函数

[复制链接]
发表于 2012-1-8 18:50:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
f(x)=   x2+1   x<0
f(x)=   100     x=0
f(x)=   2x+5     x>0


我做的:

#include <stdio.h>
main()
{
        int x;
        scanf("%d",&x);
        switch(x)
        {
        case (x>0 ) :printf("fx=%d\n",2*x+5);break;
        case (x==0) :printf("fx=100\n");     break;
        case (x<0 ) :printf("fx=%d\n",x*x+1);break;
        default:printf("error\n");
        }
}


#include <stdio.h>
main()
{
        int fx,x;
        scanf("%d",&x);
        if(x>=0)
        {
                fx=x*2+5;
                printf("fx=%d\n",fx);
        }
        if(x==0)
        {       
                fx=100;
                printf("fx=%d\n",fx);
        }
        if(x<0)
        {
                fx=x*x+1;
                printf("fx=%d\n",fx);
        }
}



两个都有问题,大家帮帮忙,谢了!
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-1-9 18:12:49 | 显示全部楼层
不能用switch做,因为int数目太多不可能一一枚举。
用if的版本里把
if(x>=0)
改为 if(x>0)
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-1-9 18:15:37 | 显示全部楼层
本帖最后由 sankeyou 于 2012-1-9 18:23 编辑

if else 版
  1. #include <stdio.h>
  2. main()
  3. {
  4.         int fx,x;
  5.         scanf("%d",&x);
  6.         if(x>0)
  7.         {
  8.                 fx=x*2+5;
  9.                 printf("fx=%d\n",fx);
  10.         }
  11.         else if(x==0)
  12.         {        
  13.                 fx=100;
  14.                 printf("fx=%d\n",fx);
  15.         }
  16.         else if(x<0)
  17.         {
  18.                 fx=x*x+1;
  19.                 printf("fx=%d\n",fx);
  20.         }
  21. }
复制代码


小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-1-9 18:20:51 | 显示全部楼层
本帖最后由 sankeyou 于 2012-1-9 18:22 编辑

switch版:


  1. #include <stdio.h>
  2. void main()
  3. {
  4.     int fx = 0, x = 0, i = 0;
  5.     scanf("%d",&x);

  6.     i = (x > 0 ? 1 : (x == 0 ? 0 : -1));

  7.     switch(i)
  8.     {
  9.     case -1:
  10.         fx=x*x+1;
  11.         printf("fx=%d\n",fx);
  12.         break;
  13.     case 0:
  14.         fx=100;
  15.         printf("fx=%d\n",fx);
  16.         break;
  17.     case 1:
  18.         fx=x*2+5;
  19.         printf("fx=%d\n",fx);
  20.         break;
  21.     }               
  22. }
复制代码


小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-10 16:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表