- /*
- * Copyright (c) 2014, 烟台大学计算机学院
- * All rights reserved.
- * 文件名称:test.cpp
- * 作 者:刘畅
- * 完成日期:2014年 10 月 16 日
- * 版 本 号:v1.0
- *
- * 问题描述:输入x的值(要求为实型),根据公式计算并输出y的值;
- * 输入描述: 一个变量x,代表输入的值;
- * 程序输出:一个变量y,代表输出的值。
- */
- (1)if~else~语句
#include <iostream> #include <cmath> using namespace std; int main() { double x,y; cout<<"x="; //提示输入 cin>>x; //输入x的值 if (x<2) //进行判断 y=x; //进行第一种情况的运算 else if (x<6) y=x*x+1; //进行第二种情况的运算 else if (x<10) y=sqrt(x+1); //进行第三种情况的运算 else y=1/(x+1); //进行第四种情况的运算 cout<<"y="<<y<<endl; //输出y的值 return 0; }
- (2)switch语句第一种
#include <iostream> #include <cmath> using namespace std; int main() { double x,y; int t; cout<<"x="; //提示输入 cin>>x; //输入x的值 t=x/2; //确定表达式的值 switch (t) //准备进行switch语句 { case 0:y=x;break; //第一种情况(当x<2时) case 1: case 2:y=x*x+1;break; //第二种情况(当x>=2&&x<6时) case 3: case 4:y=sqrt(x+1);break; //第三种情况(当x>=6&&x<10时) default:y=1/(x+1); //第四种情况 (当x>=10时) } cout<<"y="<<y<<endl; //输出y的值 return 0; }
- (3)switch语句第二种
#include <iostream> #include <cmath> using namespace std; int main() { double x,y; int t; cout<<"x="; //提示输入 cin>>x; //输入x的值 t=(x<2)+(x<6)+(x<10); //确定表达式的情况 switch (t) //准备进行switch语句 { case 3:y=x;break; //第一种情况(当x<2时) case 2:y=x*x+1;break; //第二种情况(当x>=2&&x<6时) case 1:y=sqrt(x+1);break; //第三种情况(当x>=6&&x<10时) case 0:y=1/(x+1); //第四种情况 (当x>=10时) } cout<<"y="<<y<<endl; //输出y的值 return 0; }
- 运行结果:
-
- 知识点总结:
- 初步的掌握了if~else和switch语句的运用,特别是学会了两种运用switch的不同解法,使运行步骤更加多元化。还学会了运用&&。
- 学习心得:
- 在if~else~嵌套中取了个巧,没有在if后面的括号中使用&&使表述更加清楚,因为打字打得背疼,以后得多锻炼锻炼了,不过能成功的用两种不同的语句并且都成功运行,很开心啊
第8周项目3-多分段函数求值(if~else~语句1种+switch语句2种)
最新推荐文章于 2022-10-30 23:06:11 发布