c++ - 函数和 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);
}
解决方案
单独想象一下这段代码:
double power ()
{
double result = 1;
for(int i=0; i < exponent; i++)
{
result = result * base;
}
return result;
}
你能告诉我它们是什么base
以及exponent
它们来自哪里吗?
答案是不。如果你不能说,编译器也不能。在我的代码中,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
and的变量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
无关。exponent
print_power2
3
如果我再次对数学符号进行类比:
f(x) = x * 2
g(x) = f(x * 2) / 3
尽管g
和f
都x
作为参数,但它x
是不同的,并且在每个函数中占用不同的值。
推荐阅读
- laravel - Vue Laravel:角色、权限和用户管理
- javascript - if 语句在两个 for 循环内不返回任何内容
- node.js - 为什么我用mongoose将它保存在mongoDB中后无法获取数据库中的记录?
- python - 使用 selenium单击带有标签的元素
- android - Android Kotlin 使用 Safe Args Navigation 传递数据返回 null
- processing - 碰撞后反弹不起作用,并且物体通过地形剪辑
- c++ - C++ 对象构造——直接初始化与使用“=”操作符,它们是等价的吗?
- c++ - 如何检查对象是否是 C++ 中模板类的实例?
- azure - 为什么 Azure AD B2C 使用代码而不是 id_token 重定向?
- sql - Group By子句SQL中不同条件的比率