C++局部变量改变值

标签 c++ local

我有以下 C++ 函数,它试图在负整数和正整数数组中找到最大子数组和

int  MaxSubArray::find_max_subarray(void) {
  int maxsofar =0 ;
  int maxendinghere = 0;
  for(int i = 0;i <= arr_size; i++) {
    cout << "maxending here is: " << maxendinghere << endl;
    cout << "maxsofar is: " << maxsofar << endl;
    maxendinghere += array[i];
    maxendinghere = max(0,maxendinghere);
    maxsofar = max(maxendinghere,maxsofar);
  }
  int retvalue = maxsofar;
  cout << "Max so far final is" << maxsofar << endl;
  cout << "Max ending here is " << maxendinghere << endl;
  return retvalue;

}

对于包含 10,20,30,-50,50 的数组,我得到以下输出

maxending here is: 0
maxsofar is: 0
maxending here is: 10
maxsofar is: 10
maxending here is: 30
maxsofar is: 30
maxending here is: 60
maxsofar is: 60
maxending here is: 10
maxsofar is: 60
maxending here is: 60
maxsofar is: 60
Max so far final is135205
Max ending here is 135205
Max sub array is 135205

谁能告诉我为什么变量 maxsofar 在 for 循环之外将值更改为 135205。 提前致谢

最佳答案

不应该是:

for(int i = 0; i < arr_size; i++)

?

请注意,您在打印完 后的最后一个循环迭代中修改了 maxsofar,这就是为什么您会看到差异的原因 - 您可能添加了垃圾由于你的逐一循环边界,最后一次迭代的值。

希望您喜欢Programming Pearls

关于C++局部变量改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7287710/

相关文章:

c++ - 关于使用指向成员函数的指针的困境

c++ - Winsock教程错误

仅适用于本地开发人员的 PHP、postfix、sendmail、thunderbird

xcode - 每次关闭应用程序时都会播放本地通知

javascript - 访问所有存储的 cookie

c++ - 在 Ubuntu 中使用 vscode 编译 cpp 文件

c# - 如何旋转二维整数数组

php - 在本地计算机之间移动 WP 站点后出现警告

C++ 加载文件

java - 如何设置 Controller 类的变量名以便所有模型 View 都可以访问该变量值?