一、参数使用
For a function to use arguments, it must declare formal parameters, which are variables that accept the argument's values.
{
cout << x;
}
You can pass different arguments to the same function.
int timesTwo(int x) {
return x*2;
}
int main() {
cout << timesTwo(8);
// Outputs 16
cout <<timesTwo(5);
// Outputs 10
cout <<timesTwo(42);
// Outputs 84
}
二、多参数
函数中可以定义多个参数,中间用“,”隔开。例如 int addNumbers(int x, int y)
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
int main() {
cout << addNumbers(50, 25);
// Outputs 75
}
三、rand() Function 随机数函数
使用rand()时需要添加头文件#include <cstdlib>
使用%(modulo)去限定随机数的范围。
int main () {
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 6) << endl;//rand()%6 即取小雨6的随机数,若要进行其他运算加括号
}
}
实际上,rand()是个伪随机数函数,每次产生的随机数序列都是相同的。
而srand()可以产生真正的随机数。。下面用time()等函数产生真正随机数。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main () {
srand(time(0));
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 6) << endl;
}
}
四、递归函数 recursive function is a function that calls itself
int factorial(int n){
if (n==1){
return 1;
}
esle{
return n*factorial(n-1);
}
}
该函数在主体中又调用了自己,构成递归函数。
五、两种方式传递参数