例4-5(嵌套调用)
输入两个整数,求其平方和(调用函数)
分析:本例中定义了平方函数fun2(),然后定义了平方和函数funl(),由主函数
main()调用fun1(),funl()又调用了fun2()。
源程序:
#include <iostream>
using namespace std;
int fun2(int m)
{
return m * m;
}
int fun1(int x, int y)
{
return fun2(x) + fun2(y);
}//两个被调函数定义完毕
int main()
{
int a, b;
cout << "Please enter two integers(a and b): ";
cin >> a >> b;
cout << "The sum of square of a and b:" << fun1(a, b) << endl;
system("pause");
return 0;
}
system("pause") 的用处:
很多时候,我们程序运行的exe窗口往往会一闪而过。此时,在程序的末尾加上一句“system("pause")”就可以让窗口始终保持在我们用户的运行页面上
书P63:
在调用函数之前,盖要对每一个被调用的函数进行声明。
这里书上说的也没错,但是并不全对;
我们如果要先写主函数,再定义被调函数也可以。只不过如果要这样(操作)的话,要记得:
在主函数的开头就必须要对被调函数进行声明。具体实际编写改动的程序如下:
#include <iostream>
using namespace std;
int main()
{
int fun1(int x, int y);
int fun2(int m);//这里我们对被调函数进行声明
int a, b;
cout << "Please enter two integers(a and b): ";
cin >> a >> b;
cout << "The sum of square of a and b:" << fun1(a, b) << endl;
system("pause");
return 0;
}
int fun2(int m)
{
return m * m;
}
int fun1(int x, int y)
{
return fun2(x) + fun2(y);
}//两个被调函数的定义
#include <iostream>
using namespace std;
int main()
{
int fun1(int x, int y);
int fun2(int m);//这里我们对被调函数进行声明
int a, b;
cout << "Please enter two integers(a and b): ";
cin >> a >> b;
cout << "The sum of square of a and b:" << fun1(a, b) << endl;
system("pause");
return 0;
}
int fun2(int m)
{
return m * m;
}
int fun1(int x, int y)
{
return fun2(x) + fun2(y);
}//两个被调函数的定义
例4-6
求n!
分析:计算n!的公式为
n!=1(n=0);
n!=n\n(n-1)! (n>0)
我写的:
#include <iostream>
using namespace std;
int A(int i)
{
int x;
if (i == 0)
x = 1;
else
x = i * A(i - 1);
return x;
}
int main()
{
int x, y, z;
cout << "请输入您要求几的阶乘" << endl;
cin >> x;
y = A(x);
cout << "您想要的结果为:" << endl;
cout << y << endl;
}
#include <iostream>
using namespace std;
int A(int i)
{
int x;
if (i == 0)
x = 1;
else
x = i * A(i - 1);
return x;
}
int main()
{
int x, y, z;
cout << "请输入您要求几的阶乘" << endl;
cin >> x;
y = A(x);
cout << "您想要的结果为:" << endl;
cout << y << endl;
}
标准答案,源程序:
#include <iostream>
using namespace std;
unsigned fac(int n)
{
unsigned f;
if (n == 0)
f = 1;
else
f = fac(n - 1) * n;
return f;
}
int main()
{
unsigned n;
cout << "Enter a positive integer:";
cin >> n;
unsigned y = fac(n);
cout << n << "!=" << y << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
unsigned fac(int n)//阶乘的英文:factoial
{
unsigned f;
if (n == 0)
f = 1;
else
f = fac(n - 1) * n;
return f;
}
int main()
{
unsigned n;
cout << "Enter a positive integer:";
cin >> n;
unsigned y = fac(n);
cout << n << "!=" << y << endl;
system("pause");
return 0;
}
当然,这里的函数的输入范围自然也要在保证输出结果是能在int范围之内的,不然的话不管输入什么,最终结果输出都报0,例: