2012-12-11 2 views
-1

나는 주기적으로 호출되는 프로그램을 만들었다. 가치 T가 변할 때마다 나는 이전주기의 T와 T 값을 비교하고 매주기마다 그것을하고 싶습니다.두 연속 반복 단계를 어떻게 비교할 수 있습니까? C++에서

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; 

어떻게해야 제대로 할 수 있습니까? 모든 다음에 ... 그런 식으로

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; 
} 

을 : 나는이 시도했지만 여전히 T는 여기에 선언되지 않은 :

int T; 
int prevT; 
if (prevT != T) 
    prevT = 0; 
else 
    prevT = externalsrc; 
int comparison = prevT - T; 
prevT = T; 
+0

처럼 될 것입니다. 첫 번째 값을 정의하는 방법은이 값이 사용되는 방식에 전적으로 의존하며, 이에 대해서는 전혀 알지 못합니다. –

+0

질문은 실제로 여기에 어떻게 이전 단계에서 값 T를 포함 할 변수를 소개 할 수 있습니다. 이전 단계가없는 첫 번째 단계를 제외하고는 언제나 잘 돌아갈 것입니다. 나는이 프로그램을 호출하는 모든 사이클에서 prevT가 0이 될 것이기 때문에 이것을 0으로 초기화 할 수 없다. 그래서 나는 그것에 대한 알고리즘 솔루션이 부족합니다. – berndh

+0

정확하게 이해한다면, 다음에 프로그램을 실행할 때 값을 파일에 저장하고로드해야합니다. – jrok

답변

2

를 첫 번째 대답을 사용할 수 있지만 0으로 static 및 초기화로 prevT 선언 반복에서는 prevT의 초기화가 무시되고 값은 마지막 반복에서 보존됩니다.

+0

완벽한, 고마워! – berndh

+0

클래스에서이 동작을 마무리하는 것이 정적을 사용하는 것보다 훨씬 낫습니다. –

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 
} 
0
struct compare 
{ 
    compare() { prev = 0; } 

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

     return cmp; 
    } 
private: 
    int prev; 
}; 
1

당신은 당신의 함수 내 static로 prevT을 정의 할 수 있습니다. 이 코드 질문 인 경우

코드는 내가 확실하지 오전이

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; 
관련 문제