0

考虑以下代码:

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 初始化为零时,它将在后续迭代中执行,我不会得到我需要的东西。

有任何想法吗?提前致谢

4

3 回答 3

3

你应该做到static

static int temp1 = 0;

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

于 2013-04-26T11:50:01.973 回答
1

可能的解决方案:

  • temp1代码及其初始化移出代码并传递temp1给函数(我假设上面的代码在函数中)。调用代码将管理temp1并确保它与传递给函数的变量相同:

    void moving_average_func(int& a_temp1)
    {
    }
    
    int temp1 = 0;
    moving_average_func(temp1);
    moving_average_func(temp1);
    
  • temp1创建一个变量,static以便初始化只发生一次:

    static int temp1 = 0;
    

static如果多个线程使用相同的代码块(因为多个线程将temp1在解决方案中访问相同的代码块),则使用非解决方案重新开始计算会更简单,并且可以避免同步要求static

于 2013-04-26T11:50:19.233 回答
0

You can make temp1 a static variable, such that it retains its value between function calls. This way it will only be be initialized to zero the first time the function is called - note it is automatically initialized to zero (as per the standard), so you don't have to do it explicitly yourself. Example of how it works:

#include <iostream>

using namespace std;

void asd()
{
    static int a=1;
    cout << a << endl;
    a++;
}

int main()
{
    asd(); //outputs 1
    asd(); //outputs 2
    return 0;
}
于 2013-04-26T11:58:41.627 回答