-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 に答える