[项目4:多分数段函数求值](C语言)
一、问题及代码
/*
* 文件名称:Ex3-1.cpp
* 作 者:刘俊博
* 完成日期:2017 年 3 月 24 日
* 版 本 号:v1.0
* 对任务及求解方法的描述部分:
* 输入描述:x
* 问题描述:多分数段函数求值
* 程序输出:y
* 问题分析:
* 算法设计:
*/
#include<stdio.h>
#include<math.h>
int main()
{
float x,y;
printf("请输入x:\n");
scanf("%f",&x);
if(x<2){
y=x;
printf("y=%f\n",y);}
else if(x<6){
y=x*x+1;
printf("y=%f\n",y);}
else if(x<10){
x=x+1;
y=sqrt(x);
printf("y=%f\n",y);}
else{
y=1/(x+1);
printf("y=%f\n",y);}
return 0;
}
二、运行结果:
三、心得体会:if语句后要跟多个语句是要注意加花括号。
四、知识点总结:使用if-else嵌套语句可以进行多路判断
【项目2:本月有几天?】
一、问题及代码:
/*
* 文件名称:作业3.cpp
* 作 者:刘俊博
* 完成日期:2017 年 3 月 24 日
* 版 本 号:v1.0
* 对任务及求解方法的描述部分:
* 输入描述:年份和月份
* 问题描述:求本月天数
* 程序输出:本月天数
* 问题分析:略
* 算法设计:略
*/
#include<iostream>
using namespace std;
int main()
{
int year,month,a;
cout<<"请输入年份和月份:\n";
cin>>year>>month;
if((!(year%4)&&year%100||!(year%400)==1)&&month==2)
cout<<"本月29天\n";
else{
switch(month){
case 1:cout<<"本月31天\n";break;
case 2:cout<<"本月28天\n";break;
case 3:cout<<"本月31天\n";break;
case 4:cout<<"本月30天\n";break;
case 5:cout<<"本月31天\n";break;
case 6:cout<<"本月30天\n";break;
case 7:cout<<"本月31天\n";break;
case 8:cout<<"本月31天\n";break;
case 9:cout<<"本月30天\n";break;
case 10:cout<<"本月31天\n";break;
case 11:cout<<"本月30天\n";break;
case 12:cout<<"本月31天\n";break;}}
return 0;
}
二、运行结果
三、心得体会:使用与或非要注意优先级,不然可能会出错。
四、知识点总结:switch语句中case通常与break语句配合,保证多路分支的正确实现。
【项目3:定期存款利息计算器】
一、问题及代码
/*
* 文件名称:作业3.cpp
* 作 者:刘俊博
* 完成日期:2017 年 3 月 24 日
* 版 本 号:v1.0
* 对任务及求解方法的描述部分:
* 输入描述:存款金额和期限
* 问题描述:求利息和本利和
* 程序输出:利息和本利和
* 问题分析:略
* 算法设计:略
*/
#include<iostream>
using namespace std;
int main()
{
double money,interest,amount;
const double A=0.031;
const double B=0.033;
const double C=0.035;
const double D=0.044;
const double E=0.05;
const double F=0.055;
int year;
cout<<"请输入存款金额:";
cin>>money;
cout<<"======存款期限======\n";
cout<<"1. 3个月\n";
cout<<"2. 6个月\n";
cout<<"3. 一年\n";
cout<<"4. 两年\n";
cout<<"5. 三年\n";
cout<<"6. 四年\n";
cout<<"请选择存款期限的代号:";
cin>>year;
switch(year){
case 1:{interest=money*A*0.25,amount=money+interest;
cout<<"到期利息为:"<<interest<<"元,本息合计共"<<amount<<"元。\n";break;}
case 2:{interest=money*B*0.5,amount=money+interest;
cout<<"到期利息为:"<<interest<<"元,本息合计共"<<amount<<"元。\n";break;}
case 3:{interest=money*C*1,amount=money+interest;
cout<<"到期利息为:"<<interest<<"元,本息合计共"<<amount<<"元。\n";break;}
case 4:{interest=money*D*2,amount=money+interest;
cout<<"到期利息为:"<<interest<<"元,本息合计共"<<amount<<"元。\n";break;}
case 5:{interest=money*E*3,amount=money+interest;
cout<<"到期利息为:"<<interest<<"元,本息合计共"<<amount<<"元。\n";break;}
case 6:{interest=money*F*4,amount=money+interest;
cout<<"到期利息为"<<interest<<"元,本息合计共"<<amount<<"元。\n";break;}
}
cout<<"感谢您的使用,欢迎下次光临!\n";
return 0;
}
二、运行结果
三、心得体会:使用const可以定义常量,使其不会发生改变。
四、知识点总结:使用const和使用#define效果一样,用来定义常量,提高编程效率。