根据我的理解,函数和void函数可以被调用,并且它们将在其中执行代码。
然而,我不明白括号内的变量的用途。即使少了其中一个,代码也无法运行。然而,似乎您可以为这些变量分配不同的名称,它仍然可以工作。
这些变量是如何相互联系/相互作用的?指:
1.)双倍幂(双基,int指数)
2.)void print_pow(双基,int指数)
3.)print_pow(基数、指数);
#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);
}
想象一下这段代码本身:
double power ()
{
double result = 1;
for(int i=0; i < exponent; i++)
{
result = result * base;
}
return result;
}
你能告诉我什么是基数
和指数
以及它们是从哪里来的吗?
答案是否定的。如果你不能说,编译器也不能说。在我的代码中,没有声明base
和exponent
。
这些被称为函数参数。他们完全是他们听起来的样子。可以用数学符号做一个很好的类比:
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
的值。
函数参数的一个重要性质是它们的作用就像局部变量一样。这种本地实体不受外部实体名称的影响。因此,如果在您的代码中,它们是名为base
和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
中的值也不会相同。您甚至可以注意到,power
中的exponent
将与print_power2
中的exponent
没有关系,因为我发送了常数3
。
如果我再对数学符号做一个类比:
f(x) = x * 2
g(x) = f(x * 2) / 3
即使g
和f
都具有x
作为参数,但x
是不同的,并且在每个函数中使用不同的值。
这里应用的命名方案有点不幸。这些变量的名字几乎可以是任何东西,最好花点时间找到好的名字。不过,为了说明它们是不同的实体,我只是把它们变得不同:
#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 a, int b)
{
double myPower = power (a, b);
cout << a << " raised to the " << b << " power is " << myPower << ". \n ";
}
int main()
{
double x;
int y;
cout << "What is the base?: ";
cin >> x;
cout << "What is the exponent?: ";
cin >> y;
print_pow(x, y);
}
变量是在一定范围内声明的。只有在此范围内,您才能访问该变量。在您的代码中有3
不同的变量,称为base
。那之间并没有神奇的关系,只是因为他们有相同的名字。它们通过使用参数print_pow(x,y)
调用函数来“连接”,参数的名称与函数无关,函数参数的名称与调用者无关(除了提示参数的用途)。