首页 > 解决方案 > C++ rand() 在第一次运行时返回无意义的值,在第二次运行正常

问题描述

我正在制作一个彩票程序,这是我的随机函数

#include <iostream>
#include <stdlib.h>
#include <time.h>// for seeding srand
#include <algorithm> //for std::find
#include <iterator> //for std::begin, std::end

using namespace std;

void rivinArvonta(int arvottuRivi[]){   
    int rivi[7];
    int pallo = 41;
    srand(time(NULL));

    for (int i = 0; i < 7; i++) {
            pallo = rand() % 40 + 1;
            bool exists = (find(begin(rivi), end(rivi), pallo) != end(rivi));
            if (exists == false) {
                    rivi[i] = pallo;
            }else
                    i = i - 1;
    }
    sort(rivi, rivi + 7);


    for (int i = 0; i < 7; i++){
        arvottuRivi[i] = rivi[i];
    }
}

该程序在一个while循环中运行,直到我告诉它停止。我第一次调用此函数时,它返回如下内容:

 5, 0, -164820691, 21983, 0, 0, -164820768

我第二次调用该函数时,它按预期工作。

我不明白怎么pallo = rand() % 40 + 1;能返回这么多超出范围的东西?这可能是因为我使用了 g++ 吗?

PS 很抱歉我的变量名是芬兰语。

标签: c++random

解决方案


rivi第一次是未初始化的数据,所以你会得到阿德里安摩尔建议的垃圾。第二次调用将在第一次调用初始化后使用相同内存位置中的相同数组,这就是您获得合理结果的原因。也不要为有幸会说其他语言而道歉!


推荐阅读