首页 > 解决方案 > 函数和 void 函数之间的变量如何工作/相互作用?

问题描述

观看此https://youtu.be/_bYFu9mBnr4教程。据我了解,可以调用函数和 void 函数,它们将在其中执行代码。

但是我不明白括号内变量的目的。如果缺少其中一个,该代码将无法工作。但是,您似乎可以为这些变量分配不同的名称,并且它仍然可以工作。

这些变量如何相互连接/相互作用?参考:

1.) 双倍幂(双底,int 指数)

2.) void print_pow (双底,int 指数)

3.) print_pow (base, exponent);

#include <iostream>
#include <cmath>

using namespace std;

double power(double base, int exponent)
{ 
    double result = 1;
    for(int i=0; i < exponent; i++)
    {
        result = result * base;
    }
    return result;
}

void print_pow(double base, int exponent)
{
    double myPower = power (base, exponent);
    cout << base << " raised to the " << exponent << " power is " << myPower << ". \n ";
}

int main()
{ 
    double base;
    int exponent;
    cout << "What is the base?: ";
    cin >> base;
    cout << "What is the exponent?: ";
    cin >> exponent;
    print_pow(base, exponent);
}

标签: c++

解决方案


单独想象一下这段代码:

double power ()
{ 
    double result = 1;
    for(int i=0; i < exponent; i++)
    {
        result = result * base;
    }
    return result;
}

你能告诉我它们是什么base以及exponent它们来自哪里吗?

答案是不。如果你不能说,编译器也不能。在我的代码中,baseexponent没有被声明。

这些被称为函数参数。它们正是它们听起来的样子。可以用数学符号做一个很好的类比:

f(x) = x * 2

括号中是函数的参数。


现在考虑一个与您的代码非常相似的代码,但参数名称已更改:

double power(double base, int exponent)
{ 
    double result = 1;
    for(int i=0; i < exponent; i++)
    {
        result = result * base;
    }
    return result;
}

// Name changed!  ----v------v
void print_pow(double b, int e)
{
    double myPower = power(b, e);
    cout << base << " raised to the " << exponent << " power is " << myPower << ". \n ";
}

如您所见,参数可以独立于它们的名称相互映射。base将取 的值b并将exponent取 的值e

函数参数的一个重要属性是它们就像局部变量一样。这种本地实体不受外部实体名称的影响。因此,如果在您的代码中它们是多个名为baseand的变量exponent,它们是不同的实体,因为它们具有不同的作用域

如果你愿意,你可以编写这样的函数:

void print_pow2(double base, int exponent)
{
    double myPower = power(base * 2, 3);
    cout << base << " raised to the " << exponent << " power is " << myPower << ". \n ";
}

如您所见,即使名称相同,base内部exponent的值也不相同power。您甚至可以注意到,当我发送常量时,exponent内部与inpower无关。exponentprint_power23

如果我再次对数学符号进行类比:

f(x) = x * 2
g(x) = f(x * 2) / 3

尽管gfx作为参数,但它x是不同的,并且在每个函数中占用不同的值。


推荐阅读