c++ - 在初始案例后将值传递给变量

标签 c++

考虑以下代码:

int s= int(sr/nt);
int temp1 = 0; //initialization for the first time case

// the following is the logic for the subsequent cases
int temp2= temp1; // a non-zero value of 's', calculated previously and stored in temp1 is now transferred to temp2
temp1 = s; // currently calculated value of 's' stored in temp1

double moving_average = (temp1+temp2)/2; // not relevant to the problem

我的问题是我要求上面的代码在调用时运行多次;并需要存储在 temp1 中的“s”的先前值将其传输到 temp2 以计算移动平均值。

当我在代码中将 temp1 初始化为零时,它将在后续迭代中执行,但我不会得到我需要的东西。

有什么想法吗?提前致谢

最佳答案

你应该让它static

static int temp1 = 0;

这将确保它只被初始化一次,此后不会被重新初始化。

关于c++ - 在初始案例后将值传递给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16235663/

相关文章:

c++ - 为什么 C++ 析构函数在继承时被调用 2 次

c++ - Windows 10 桌面窗口管理器交换时间?

c++ - LLVM 在 std::vector 中存储 Loop*

c++ - 使用 Armadillo 时 dgssvx 中的非法值

c++ - 使用 C++ 与 PC 摄像头交互

C++:派生类, "no matching constructor"错误

C++ 提取 istream 的内容并复制到另一个

C++ 可移植浮点位表示?

c++ - STL风格算法: how to manage output iterator

C++0x 嵌套初始化列表