记录变量的值

recording the value of a variable

本文关键字:变量 记录      更新时间:2023-10-16

我想知道如何记录一个变量的前一个值。这个问题的一个例子是下面的代码:

int distanceFormula(int x1, int x2, int y1, int y2){
  int distance;
  distance = sqrt(pow((x1-x2), 2) + pow((y1-y2), 2));
  return distance;
}
int main(){
  for(int i = 0; i < 2; i++){
    int x = rand() % 180;
    int y = rand() % 180;
    int x2 = rand() % 180;
    int y2 = rand() % 180;
    int distance = distanceFormula(x, x2, y, y2);
    int priordistance = distanceFormula(x, x2, y, y2);
    if(priordistance != distance){
      cout<<"Yes! It worked!"<<endl;
    }
  }
  return 0;
}

代码本身不会返回"是的!它起作用了!"如何记录以前的距离值,然后将以前的值与当前值进行比较?

编辑:感谢您的快速评论!真的很感激。

为了澄清实际问题,上面的代码只是一个快速模板/示例。由于距离值将在第二次循环时发生变化,如何记录第一个距离值并将该值设置为先验距离,然后将当前距离值与先验距离(其值实际上只是以前的距离值)进行比较。

只需在变量中重做上一个值。

#include <cmath>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
int distanceFormula(int x1, int x2, int y1, int y2){
  int distance;
  distance = sqrt(pow((x1-x2), 2) + pow((y1-y2), 2));
  return distance;
}
int main(){
  int priordistance = 0; // a variable used to record the value
  for(int i = 0; i < 2; i++){
    int x = rand() % 180;
    int y = rand() % 180;
    int x2 = rand() % 180;
    int y2 = rand() % 180;
    int distance = distanceFormula(x, x2, y, y2);
    if(i > 0 && priordistance != distance){ // use i > 0 to avoid compareing with meaningless value
      cout<<"Yes! It worked!"<<endl;
    }
    priordistance = distance; // record the value
  }
  return 0;
}

有几种方法可以做到这一点。。。您可以在for循环之外定义优先级距离,并确保只重新定义一次(因为您循环了两次)。

然而,这不是我要做的,我会简单地创建一个整数数组,其中包含n个"距离",供您通过索引I 参考

int[] or int *

您可以做各种事情。您需要在整个for循环中保持该值。请注意,在您已经获得一个先前的值之前,进行比较是没有意义的。

int main(){
  int priordistance = 0; //lifetime outside for loop
  for(int i = 0; i < 2; i++){
    int x = rand() % 180;
    int y = rand() % 180;
    int x2 = rand() % 180;
    int y2 = rand() % 180;
    int distance = distanceFormula(x, x2, y, y2);
    if(i && priordistance != distance){
     //^---- have we got a prior value yet?  
      cout<<"Yes! It worked!"<<endl;
    }
    priordistance = distance;//remember for next time
  }
  return 0;
}

你的意思是这样的吗?

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
int distanceFormula( int x1, int x2, int y1, int y2 )
{
    int distance;
    distance = std::sqrt( std::pow( x1 - x2, 2 ) + std::pow( y1 - y2, 2 ) );
    return distance;
}
int main() 
{
    const size_t N = 2;
    int distance[N];
    std::srand( ( unsigned int )std::time( nullptr ) );
    for ( size_t i = 0; i < N; i++ )
    {
        int x  = rand() % 180;
        int y  = rand() % 180;
        int x2 = rand() % 180;
        int y2 = rand() % 180;
        distance[i] = distanceFormula( x, x2, y, y2 );
    }
    if ( distance[0] != distance[1] ) std::cout << "Yes! It worked!" << std::endl;
    return 0;
}

程序输出为

Yes! It worked!