分段函数求值


写了几个小程序,加强对 switch case 语句的理解和应用。
/*
#include <iostream>
using namespace std;


int main()
{
    int x=1,a=0,b=0;
    switch(x)
    {
        case 0: a++;break;
        case 1: b++;
        case 2: a++; b++;break;
        case 3: a++; b++;
    }




    cout <<"a ="<<a<<endl;
    cout <<"b="<<b<<endl;
    return 0;
}


*/
///
/*
#include <iostream>
using namespace std;


int main()
{
    int i = 10,j,m = 0,n = 0;
    j = i % 3;
    switch(j)
    {
        case 0: m++;break;
        case 1:
        case 2: n++; break;
        default: cout <<"i="<< i <<endl;
    }
    cout <<"m="<< m <<",n="<< n <<endl;
    return 0;
}


//swich case 语句,当case后面没有break时,不跳出switch 结构,
//继续执行下一条case语句,不管case语句是否满足条件
*/

/

编写程序 ,实现以下分段函数求值。


/*
#include <iostream>
#include <Cmath>
using namespace std;
int main()
{
    double x,y;
    cout <<"请输入大于0 的实数值x"<<endl;
    cin >> x;
    if(x < 0)
        cout<<"Input error!"<<endl;
    else
    {


            if(x >= 0 & x < 2)
                y = x;
            else if(x >= 2 & x < 6 )
                y = x*x + 1;
            else if( x >= 6 & x < 10)
                y = sqrt(x + 1);
            else
                y = 1/(x + 1);
            cout <<"y = "<< y <<endl;
    }
    return 0;
}


*/

#include <iostream>
#include <Cmath>
using namespace std;
int main()
{
    double x,y;
    int c;
    cout <<"请输入大于0 的实数值x"<<endl;
    cin >> x;
    if(x < 0)
        cout<<"Input error!"<<endl;
    else
    {
        c = int (x)/2;
        switch(c)
        {
        case 0:
            y = x;break;
        case 1:
        case 2:
            y = x * x + 1;break;
        case 3:
        case 4:
            y = sqrt(x + 1);break;
        default:
            y = 1/(x + 1);break;
        }
            cout <<"y = "<< y <<endl;
    }
}
切记,C++ 编程语言,不支持 switch case 语句  case x>= 0 && x < 2:y = x + 1; 这种语句格式。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值