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