考虑以下代码:
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/