繁体   English   中英

在 C++ 函数中按引用传递

[英]Passing by reference in C++ function

我正在编写一个简单的程序来使用函数计算 6^5。 这是我的代码

#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}

结果是

 6^5 is -683606016

而不是 7776

你们能解释一下为什么我得到这个结果吗? 我不是在寻找另一种编写此代码的方法。 我知道有更简单的方法,但我试图了解出了什么问题

你为什么使用按引用传递。 设置尽可能多的const可以减少犯错误的几率:

#include <iostream>
using namespace std;

int raiseToPower(const int base, const int exponent) {
    int result = base;
    for (int i = 1; i < exponent; i = i + 1){
        result = result * base;
    }
    return result;
}

int main() {
    int base = 6;
    cout << "6^5 is " << raiseToPower(base, 5)<< endl;

    return 0;
}

如果必须通过引用传递,您可以这样做:

#include <iostream>
using namespace std;

void raiseToPower(const int base,
                 const int exponent,
                 int &result)
{
    result = base;
    for (int i = 1; i < exponent; i = i + 1){
        result = result * base;
    }
}

int main() {
    int base = 6;
    int result;
    raiseToPower(base, 5, result);

    cout << "6^5 is " << result << endl;

    return 0;
}

你的计算不正确。 变量 base 的值不应改变。 尝试这个:

 int raiseToPower(int &base, int exponent){
   int result = 1;
   for (int i = 1; i <= exponent; i = i + 1){
      result = result * base;
    }
    return result;
 }

你可能想要这样的循环:

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

此外,您通过引用将基本参数带到 raiseToPower - 这意味着您正在更改 main 中的基本变量 - 可能不是您想要做的。

让我们考虑这个循环

 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }

在 i 等于 1 的第一次迭代之后,你有

   base= base * base;

那就是结果是base ^ 2

当 i = 2 你有

   base= base^2 * base^2;

那就是结果是基数^ 4。

当 i 等于 3 你有

   base= base^4 * base^4;

结果是基数^8。

当 i 等于 4 你有

   base= base^8 * base^8;

结果是基数^16。

结果值似乎太大而无法容纳在 int 类型的对象中。

当参数通过引用传递时,这也不是一个好主意。 第二个参数的类型应该是 unsigned int。

这是一个演示程序,展示了如何实现该功能。

#include <iostream>

long long int raiseToPower( int base, unsigned int exponent )
{
    long long int result = 1;

    while ( exponent-- )
    {
        result *= base;
    }

    return result;
}

int main() 
{
    int base = 6;

    std::cout << "6^5 is " << raiseToPower(base, 5) << std::endl;

    return 0;
}

它的输出是

6^5 is 7776

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM