我构建了一个循环调用的程序。每次值T改变,我想比较前一个周期的值T和T,并且每个周期都这样做。
int T = externalsrc; //some external source
int prevT; //cannot do it because in the first cycle it will have no value when used in comparison
int prevT = 0; //cannot do it, because in every cycle prevT will be zero for my comparison
int comparison = prevT - T;
prevT = T;
我该如何正确地做到这一点?我也试过这个,但是T还没有在这里声明:
int T;
int prevT;
if (prevT != T)
prevT = 0;
else
prevT = externalsrc;
int comparison = prevT - T;
prevT = T;
答案 0 :(得分:2)
使用您的第一个答案,但将prevT
声明为static
并将init声明为0:
while (condition) {
int T = externalsrc; //some external source
static int prevT = 0; // declaring static means that it will only be set to 0 once
int comparison = prevT - T;
prevT = T;
}
...在每次后续迭代中都会忽略prevT
的初始化,并且从最后一次迭代中保留该值。
答案 1 :(得分:1)
您可以保留一个布尔变量来告诉您它是否是第一次。
有些事情是这样的:
bool first_fime = true;
// ...
if (first_time)
{
// Do something with T only
previousT = T;
// It's no longer the first time
first_time = false;
}
else
{
// Do something with both T and previousT
}
答案 2 :(得分:1)
您可以在函数中将prevT定义为static
。
您的代码将是这样的
int T = externalsrc; //some external source
int prevT; //cannot do it because in the first cycle it will have no value when used in comparison
static int prevT = 0; //The first time it is called it will start with pr
int comparison = prevT - T;
prevT = T;
答案 3 :(得分:0)
struct compare
{
compare() { prev = 0; }
int operator() (int t)
{
int cmp;
cmp = prev - t;
prev = t;
return cmp;
}
private:
int prev;
};