您的位置:首页 > 其它

分段函数求值

2014-05-30 16:20 211 查看
写了几个小程序,加强对 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; 这种语句格式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: