c++learning--Function(2)

一、参数使用

For a function to use arguments, it must declare formal parameters, which are variables that accept the argument's values.

void printSomething(int x)
{
    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);

    }

}

        该函数在主体中又调用了自己,构成递归函数。

五、两种方式传递参数

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值