分段函数求值讲解
题:
从键盘输入x的值(要求为实型),根据以下公式计算并输出x和y的值
要求采用两种解法完成,解法1用if else 语句,解法2主体用switch 语句
注意:分段的关键点处,x的值均是偶数;x<0 是非法的输入,程序应该作出处理
Sol 1:
#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
float x,y;
cout<<"please enter x:";
cin>>x;
if (x<0)
cout<<"wrong"<<endl;
else
{
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); x为float型,1为整型,x+1为double型,则y也为double型
cout<<"x="<<x<<",y="<<y<<endl;
}
return 0;
}
Sol 2:
Switch()括号中的量不能为浮点型,因为浮点型比较存在误差,case后面只能跟常量
注意到分段的关键点处,x的值均是偶数,可以通过取整,强制类型转换 int(x)/2
#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
float x,y;
int c;
cout<<"please enter x:";
cin>>x;
if (x<0)
cout<<"wrong"<<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);
}
cout<<"x="<<x<<",y="<<y<<endl;
}
return 0;
}
个人所得税计算器
题:编写选择结构程序,输入个人月收入总额,计算出他本月应缴税款和税后收入
1 用if语句的嵌套 2 用switch 语句
同上题
当用switch语句时,可以先用if else 定义switch()括号中的变量的常量值
例:int istep;
if (dvalue<=1500)
Istep = 1;
Switch (step)
Case 1:
利息计算器:
题:输入存款金额并选择存款种类,计算出利息(不计利息税)和本息合计,要求使用switch语句,根据选择的存款种类。确定利率和存期后计算。
Sol:
#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
int type,days;
double money,period,rate,interest;
cout<<"welcome to use the interest calculator"<<endl;
cout<<"please enter the deposit:";
cin>>money;
cout<<"=====please choose the type====="<<endl;
cout<<"1, current deposit"<<endl;
cout<<"2,3months"<<endl;
cout<<"3,6months"<<endl;
cout<<"4,1 year"<<endl;
cout<<"5,2 years"<<endl;
cout<<"6,3 years"<<endl;
cout<<"7,4 years"<<endl;
cout<<"please input the code name of the type:";
cin>>type;
if (type>=1&&type<=7)
{
switch (type)
{
case 1:
cout<<"please input the days:";
cin>>days; 只有活期才需要输入天数
period=days/360.0; 不可以是360,否则得到结果为int型
rate=0.005;
break;
case 2:
period=0.25;
rate=0.031;
break;
case 3:
period=0.5;
rate=0.033;
break;
case 4:
period=1;
rate=0.035;
break;
case 5:
period=2;
rate=0.044;
break;
case 6:
period=3;
rate=0.05;
break;
case 7:
period=5;
rate=0.055;
break;
}
interest=money*period*rate;
cout<<"the interest is:"<<interest<<" yuan, the principal and interest is :"<<interest+money<<"yuan"<<endl;
}
else cout<<"error input"<<endl;
return 0;
}