学习rand()函数

时间:2014-05-25 23:08:29

标签: c++

我尝试过分析一些涉及rand()函数的概率,所以我完成了这段代码:

int vetor_aleatorio[2], vetor_aleatorio_2[2], contador_de_atribuicoes = 0;

srand(time(NULL));
do {
     contador_de_atribuicoes += 1;
     for (int i=0; i<1; i++) 
     {
        vetor_aleatorio[i] = rand() % 3 + 1;
        vetor_aleatorio_2[i] = rand() % 3 + 1;
     } 
   } while (vetor_aleatorio != vetor_aleatorio_2);

int c = contador_de_atribuicoes - 1;
std::cout << "A quantidade de atribuicoes para que o valor das duas arrays fossem iguais, foi: " << c << std::endl;

我这样做是为了尝试分析vetor_aleatorio等于vetor_aleatorio_2需要多少个赋值...但是,它永远不会完成,即使我在rand()上使用小数组和一个短的样本空间,表明该数组不平等。

有人能解释一下这是怎么回事吗? 谢谢!

3 个答案:

答案 0 :(得分:3)

排队

while (vetor_aleatorio != vetor_aleatorio_2)

您正在比较数组的地址(因为数组的名称是指向第一个条目的指针),这是不同的。

while (vetor_aleatorio != vetor_aleatorio_2)
              ^                   ^
//          this is address       and this is address too       

你可以写:

do {
     contador_de_atribuicoes += 1;
     vetor_aleatorio[0] = rand() % 3 + 1;
     vetor_aleatorio_2[0] = rand() % 3 + 1;

} while ( vetor_aleatorio[0] != vetor_aleatorio[0]);

答案 1 :(得分:2)

您正在比较两个阵列是否相同。你要比较的是指向数组开头的指针是否相同,这是永远不会成立的。您需要显式比较每个数组中的每个元素而不是数组变量本身。

答案 2 :(得分:-1)

用于比较:(放在main之前)

bool comp_vec_2( int* v1, int* v2 )
{
    for( int i=0; i<2; ++i )
        if( v1[i] != v2[i] )
            return false;
    return true;
}

请注意,您应该比较小于2的索引,而不是1 填写向量时也是如此

使用

替换条件
while ( ! comp_vec_2(vetor_aleatorio, vetor_aleatorio_2) ) ;
相关问题