#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; }
/////////////////////////////////////////////////////////////////////
编写程序 ,实现以下分段函数求值。
/*#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; 这种语句格式。