C++:试图在函数中更改局部变量

3

我正在学习函数,尝试在for循环中调用函数中的最后一个"总计(total)"值(即在函数中标记为“到目前为止的总计”),以便在主函数中打印出36(当测试数字为8时)。但是结果并未输出36。

我明白之所以无法输出36的原因是因为我将total作为局部变量处理,我认为我需要将其作为全局或静态变量来使用,但我不确定如何操作。

我尝试将其定义为静态变量,但我不确定我是否做对了,我在定义变量时在两个total变量前面写了static关键字。

#include <iostream>
using namespace std;

int sum(int count);

int main()
{
    int count;
    double num, total;

    cout << "Please enter a number: ";
    cin >> num;

    for (count = 1; count <=num;  count = count + 1)
    {
        sum(count);
    }

    cout << "Your total is: " << total << endl;
    return 0;
}

int sum(int count)
{
    double total;
    total = total + count;
    cout << "Current number: " << count << endl;
    cout << "Total so far: " << total << endl;
}

为什么不返回 total 呢?你已经将函数声明为 int。从你的函数中返回 total 并将其存储在你在主函数中定义的 total 中,或者你可以将 total 作为引用传递给你的 sum 函数,并删除 sum 中的 total 声明。 - HMD
@Hamed,实际上我已经在我的函数中尝试使用return total;,但它仍然返回0,因为您的total是0。 - Gina Cucchiara
@GinaCucchiara 因为你没有在 main() 函数中将 sum() 的返回值赋值给 total 变量。 - Remy Lebeau
就像我之前说的那样,你需要将它的返回值赋给你在主函数中声明的 total 变量。就像这样:total += sum(count); 但是请记住,你需要先初始化你的 total 变量,就像这样:double total = 0.0; - HMD
2个回答

3

main()sum()中的total都未初始化,因此得到的任何结果都是不确定的。

实际上,sum()内部的total只属于sum()本身,而main()中的total只属于main()本身。 sum()对自己的total所做的任何更改都不会影响main()中的total

您应该修改sum(),使其将main()中的total作为指针/引用传递的输入参数传递给sum(),以便sum()可以修改其值:

#include <iostream>

using namespace std;

void sum(double &total, int count);

int main()
{
    int count, num;
    double total = 0.0;

    cout << "Please enter a number: ";
    cin >> num;

    for (count = 1; count <= num; ++count)
    {
        sum(total, count);
    }

    cout << "Your total is: " << total << endl;
    return 0;
}

void sum(double &total, int count)
{
    total += count;
    cout << "Current number: " << count << endl;
    cout << "Total so far: " << total << endl;
}

实时演示


1

main()函数中的totalsum()函数中的total是不同的变量,因为它们具有不同的块作用域。

int sum(int count) {
   // such a silly pass-through implementation if you want to calculate "total"
   // do something with count
   return count;
}
// in main
double total = 0;
total += sum(count);

我认为你的意思是 return count - Remy Lebeau
@RemyLebeau,哦,是的,还没有完成修改。 - Joseph D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接