程序设计基础(实验四)
1.目的:双重循环练习与简单函数的编写。
2 题目:
(1)编写完整程序,输出由字母拼成的菱形,行数由键盘输入的正整数控制。如:当键入的数据是4时,显示结果为:
(2)编写完整程序:以左下三角形的形式,输出九九乘法表。要求使用二重循环进行控制,纵向对齐。程序的运行结果应为:
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
……
1 * 9 = 9 2 * 9=18 3 * 9 = 27 …… 9 * 9=81
(3)编写前面讲过的average函数,能够求两个数值的平均值。
(4)设计一个函数,该函数有两个形参,一个表示年份,一个表示月份,要求该函数返回该月的天数。
(5)完成斐波拉契数列的任意个数如下形式的输出,写成函数形式。
3 程序结果贴图(注意标明对应题号和进行简短说明)
题目一、
题目二、
题目三、
题目四、
题目五、
4 编程碰到的问题及总结
5 附源代码:
题目1、
#include<iostream>
#include<iomanip>
using namespace std;
int main(int argc, char* argv[])
{ cout<<"请输入一个数:";
int n;
cin>>n;
cout<<endl<<"***************************************"<<endl;
for(int i=1;i<=2*n+1;i++) //一共2n-1行
{
if(i<=n)
{
for(int j=1;j<=2*n-1;j++) //一共2n-1列
{
if(j >= n-i+1 && j<=n+i-1 )
cout<<char(i+64);
else
cout<<" ";
}
cout<<endl;
}
else
{
for(int j1=1;j1<=2*n-1;j1++) //一共2n-1列
{
if(j1 >= i-n+1 && j1 <=3*n-i-1)
cout<<char(64+2*n-i);
else
cout<<" ";
}
cout<<endl;
}
}
cout<<"***************************************"<<endl;
}
题目2、
#include<iostream> //标准输入输出流
#include<iomanip> //c++操纵运算子
using namespace std;
int main(int argc, char* argv[])
{
cout<<"****************************************"<<endl;
for (int i=1;i<=9;i++)
{
for(int j=1;j<=i;j++)
cout<<j<<"*"<<i<<"="<<std::left<<setw(4)<<i*j; //setw(3)设置三个显示空间 std::left 显示空间内左对齐
cout<<endl;
}
cout<<"****************************************"<<endl;
return 0;
}
题目3、
#include<iostream> //标准输入输出流
using namespace std;
float average(int x,int y);
int main(int argc, char* argv[])
{
int x,y;
cout<<"请输入两个数:";
cin>>x>>y;
cout<<"他们的平均数为:"<<average(x,y)<<endl;
return 0;
}
float average(int x,int y)
{
return (float) (x + y) / 2;
}
题目4、
#include<iostream>
using namespace std;
int days(int year, int month);
int main(int argc, char* argv[])
{
int year , month;
cout<<"请输入年份我、和月份:";
cin>>year>>month;
cout<<days(year,month)<<endl;
}
int days(int year,int month)
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
{
cout<<"该月的天数为31天"<<endl;
return 31;
}
case 4:
case 6:
case 9:
case 11:
{
cout<<"该月的天数为30天"<<endl;
return 30;
}
case 2: //需要判断是否为闰年
{
if(year % 400 == 0)//世纪年
{
cout<<"该月的天数为28天"<<endl;
return 28;
}
else if( year % 400 != 0 && year % 4 == 0)
{
cout<<"该月的天数为29天"<<endl;
return 29;
}
else
{
cout<<"该月的天数为28天"<<endl;
return 28;
}
}
}
}
题目5、
#include<iostream>
#include<iomanip>
using namespace std;
int fab(int n)
{
if(n>=1)
{if(n == 1 || n == 2)
return 1;
else
return fab(n-1)+fab(n-2);
}
}
int main(int argc, char* argv[])
{ cout<<"斐波那契数列:"<<endl;
cout<<"***************************************"<<endl;
for(int i = 1;i <= 40; i++)
{cout<<setw(20)<<fab(i);}
cout<<"***************************************"<<endl;
}