几道简单的编程练习

分段函数求值讲解

题:

从键盘输入x的值(要求为实型),根据以下公式计算并输出xy的值

要求采用两种解法完成,解法1if 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);   xfloat型,1为整型,x+1double型,则y也为double

cout<<"x="<<x<<",y="<<y<<endl;

}

return 0;

}

Sol 2

Switch()括号中的量不能为浮点型,因为浮点型比较存在误差,case后面只能跟常量

注意到分段的关键点处,x的值均是偶数,可以通过取整,强制类型转换 intx/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语句的嵌套  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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值