cpp中函数参数和按值传递

本文介绍了C++中参数按值传递的概念,通过`doublecube`函数展示了如何复制并操作传递的参数而不影响原始数据。此外,还提供了一个计算彩票中奖概率的示例函数`probability`,该函数计算从总数中正确选择一定数量数字的概率。在`main`函数中,用户可以输入彩票的选择总数和允许的挑选数,程序将计算并显示中奖概率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cpp通常按值传递参数,这意味着将数值参数传递给函数,而后者将其赋给一个新的变量。

double cube(double x)
double volume = cube(side) # side=5

被调用时,该函数将创建一个新的名为x的double变量,并将其初始化为5,这样,cube()执行的操作将不会影响main中的数据,因为cube使用的是side的副本,而不是原来的数据。用于接收传递的变量被称为形参。传递给函数的值被称为实参。cpp标准使用参数argument来表示实参,使用参量parameter来表示形参,因此参数传递将参数赋给参量。

在函数中声明的变量是该函数私有的,在函数被调用时,计算机将为这些变量分配内存,在函数结束时,计算机将释放这些变量使用的内存。这样的变量被称为局部变量,因为它们被限制在函数中。

1.多个参数

n_chars("R",25);

void n_chars(char,int);

2.example

// lotto.cpp -- probability of winning
#include <iostream>
// Note: some implementations require double instead of long double
long double probability(unsigned numbers, unsigned picks);
int main()
{
    using namespace std;
    double total, choices;
    cout << "Enter the total number of choices on the game card and\n"
            "the number of picks allowed:\n";
    while ((cin >> total >> choices) && choices <= total)
    {
        cout << "You have one chance in ";
        cout << probability(total, choices);      // compute the odds
        cout << " of winning.\n";
        cout << "Next two numbers (q to quit): ";
    }
    cout << "bye\n";
    // cin.get();
    // cin.get();
    return 0;
}

// the following function calculates the probability of picking picks
// numbers correctly from numbers choices
long double probability(unsigned numbers, unsigned picks)
{
    long double result = 1.0;  // here come some local variables
    long double n;
    unsigned p;

    for (n = numbers, p = picks; p > 0; n--, p--)
        result = result * n / p ; 
    return result;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值