实验2:函数的应用
#include <iostream>
usint n);
int main()
{
int n, answer;
cout << "Enter number: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci number\n";
实验项目:函数的应用
实验目的:
(1)掌握函数的定义和调用方法
(2)练习重载函数的使用
(3)练习使用系统函数
(4)使用debug调试功能,使用step into追踪到函数内部。
实验任务:
1.编写重载函数MAX1可分别求取两个整数,三个整数,两个双精度,三个双精度数的最大值。
2.用递归的方法编写函数求Fibonacci级数,观察递归调用的过程。
}
double max1(double x, double y)
{
return (x>y?x:y);
}
double max1(double x, double y, double z)
{
double temp1=max1(x,y);
return (y>z?y:z);
}
void main()
{
int x1, x2;
double d1, d2;
x1 = max1(5,6);
x2 = max1(2,3,4);
d1 = max1(2.1, 5.6);
d2 = max1(12.3, 3.4, 7.8);
cout << "x1=" <<x1 << endl;
cout << "x2=" <<x2 << endl;
cout << "d1=" <<d1 << endl;
return 0;
}
int fib (int n)
{
cout << "Processing fib(" << n << ")... ";
if (n < 3 )
{
cout << "Return 1!\n";
return (1);
}
else
{
cout << "Call fib(" << n-2 << ") and fib(" << n-1 << ").\n";
return( fib(n-2) + fib(n-1));
}
}
实验结果:
1.x1=6
x2=4
d1=5.6
d2=7.8
2.Enter number:4
Processing fib(3)...
Call fib(1) and fib(2).
2is the3th Fibonacci number
实验步骤:
1.分别编写四个同名的函数max1,实现函数重载,在main()中测试函数功能。
int max1(int x, int y)
{
return (x>y?x:y);
}
int max1(int x, int y, int z)
{
int temp1=max1(x,y);
return (y>z?y:z);
cout << "d2=" <<d2 << endl;
}
2.编写递归函数int fib(int n),在主程序中输入n的值,调用fib函数计算Fibonacci级数。公式为fib(n)=fib(n-1)+fib(n-2),n>2;fib(1)=fib(2)=1.使用if语句判断函数的出口,在程序中用cout语句输出提示信息。