-1

我构建了一个循环调用的程序。每次值 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;
4

4 回答 4

2

使用您的第一个答案,但声明prevTstatic并初始化为 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都会忽略 的初始化,并且从上次迭代中保留该值。

于 2012-12-11T11:47:25.620 回答
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
}
于 2012-12-11T11:48:01.720 回答
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;
于 2012-12-11T11:52:11.743 回答
0
struct compare
{
    compare() { prev = 0; }

    int operator() (int t)
    {
        int cmp;
        cmp = prev - t;
        prev = t;

        return cmp;
    }
private:
    int prev;
};
于 2012-12-11T11:51:50.810 回答