用c++编程分段函数编程序实现以下分段函数,X的值由键盘输入(分别用if和switch语句实现)当0≤x<10时y=sin(x)10≤x<20 y=cos(x)20≤x<30 y= ln(x+1)30≤x<40 y=-0.5x其余值输出无定义

来源:学生作业帮助网 编辑:作业帮 时间:2020/02/25 16:08:41

用c++编程分段函数
编程序实现以下分段函数,X的值由键盘输入(分别用if和switch语句实现)
当0≤x<10时y=sin(x)
10≤x<20 y=cos(x)
20≤x<30 y= ln(x+1)
30≤x<40 y=-0.5x
其余值输出无定义

//if()实现
#include<iostream.h>
#include<math.h>
void main()
{
    double x,y;
    cout<<"Enter X:";
    cin>>x;
    if(x<0)//永远二分
        cout<<"No defination\n";
    else
    {   if(x<10)
            y=sin(x);
        else
            if(x<20)
                y=cos(x);
            else
                if(x<30)
                    y=log(x+1);//ln(x+1)
                else
                    if(x<40)
                        y=-0.5*x;
                    else
                        cout<<"No defination\n";
    }
    if(x>=0&&x<40)
        cout<<"y="<<y<<endl;
}
//switch()实现
#include<iostream.h>
#include<math.h>
void main()
{
    double x,y;
    cout<<"Enter X:";
    cin>>x;
    switch(int(x/10))//注意这里的技巧
    {
    case 0:y=sin(x);cout<<"y="<<y<<endl;break;
    case 1:y=cos(x);cout<<"y="<<y<<endl;break;
    case 2:y=log(x+1);cout<<"y="<<y<<endl;break;
    case 3:y=-0.5*x;cout<<"y="<<y<<endl;break;
    default:
        cout<<"No defination"<<endl;
    }
}