第3章 函数

1.函数的定义和使用:

例题:编写程序求x 的n次方

#include <iostream>
using namespace std;
double power(double x, int n) {
double val = 1.0;
while (n--) val *= x;
return val;
}
int main()
{
cout << "5 to the power 2 is" << power(5, 2) << endl;
return 0;
}

程序运行结果:

 

2.函数的递归调用:

例题:编写程序求阶乘

#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;
return 0;
}

程序运行结果:

 

 3.随机数

 

4.数制转换(将二进制数转化为十进制数)

#include <iostream>
using namespace std;
double power(double x, int n);
int main() {
int value = 0;
cout << "enter an 8 bit binary number";
for (int i = 7; i >= 0; i--)
{
char ch;
cin >> ch;
if (ch == '1')
value += static_cast<int>(power(2, i));//强制类型转换
}
cout << "Decimal value is" << value << endl;
return 0;
}
double power(double x, int n)
{
double val = 1.0;
while (n--)
val *= x;
return val;
}

程序运行结果:

 

 5.函数的嵌套调用:

例题:编程实现求两个数的平方和

#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 integer (a and b):";
cin >> a >> b;
cout << "the sum of square of a and b:" << fun1(a, b) << endl;
return 0;
}

程序运行结果:

 

6.函数的参数传递

 

例题:输入两个整数交换后输出

#include <iostream>
using namespace std;
void swpa(int& a, int& b) {
int t = a;
a = b;
b = t;
}
int main() {
int x = 5, y = 10;
cout << "x=" << x << " y=" << y << endl;
swap(x, y);
cout << "x=" << x << " y=" << y << endl;
return 0;
}

程序运行结果:

 

7.

 

 

8.函数的内联,重载,系统函数的调用

 

 

系统函数的调用:(编程实现角度制转换为弧度制)

#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159265358979;
int main() {
double angle;
cout << "please enter an angle:";
cin >> angle;
double radian = angle * PI / 180;
cout << "sin(" << angle << ")=" << sin(radian) << endl;
cout << "cos(" << angle << ")=" << cos(radian) << endl;
cout << "tan(" << angle << ")=" << tan(radian) << endl;
return 0;
}

程序运行结果:

 

 

9.注意:

 

posted @ 2024-05-24 20:08  萌墨  阅读(66)  评论(0)    收藏  举报