if-else语句:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All gight reserved.
*文件名称:temp.cpp
*作者:邵帅
*完成时间:2014年10月16日
*版本号:v1.0
*
*问题描述:输入一个数x,当x<2时,y=x,当2<=x<6时,y=x*x+1,当6<=x<10时,y=sqrt(x+1)当x>=10时,y=1/(x+1)
*输入描述:变量x
*程序输出;变量y
*/
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x,y;
cout<<"Please press “x”"<<endl;
cin>>x;
if (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 if(x>=10)
y=1.0/(x+1);
cout<<"y="<<y<<endl;
return 0;
}
switch语句:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All gight reserved.
*文件名称:temp.cpp
*作者:邵帅
*完成时间:2014年10月16日
*版本号:v1.0
*
*问题描述:输入一个数x,当x<2时,y=x,当2<=x<6时,y=x*x+1,当6<=x<10时,y=sqrt(x+1)当x>=10时,y=1/(x+1)
*输入描述:变量x
*程序输出;变量y
*/
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
double x,y;
cout<<"Please press “x”"<<endl;
cin>>x;
t=(x<2)+(x<6)+(x<10);
switch(t)
{
case 3:y=x;break;
case 2:y=x*x+1;break;
case 1:y=sqrt(x+1);break;
case 0:y=1.o/(x+1);break;
}
cout<<"y="<<y<<endl;
return 0;
}
运行结果:
知识点总结:学习使用switch语句,了解switch语句的含义
学习心得:switch语句不能使用浮点型变量。
@ Mayuko