c++ - 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 很抱歉我的变量名是芬兰语。
解决方案
rivi
第一次是未初始化的数据,所以你会得到阿德里安摩尔建议的垃圾。第二次调用将在第一次调用初始化后使用相同内存位置中的相同数组,这就是您获得合理结果的原因。也不要为有幸会说其他语言而道歉!
推荐阅读
- graph - 在 Power BI 中向折线图添加多个字段
- javascript - 按日期排序并获取 CouchDB 视图中的最新值
- reverse-engineering - 需要 Ghidra 自动分析常见的 Microsoft C 函数
- r - 是否需要运行 DLNM 包的行数
- flutter - Flutter firebase_messaging最新版本上的FirebaseMessaging.configure()错误
- c - 算术问题:前向声明和除法后总是返回零
- oracle - ORA-03113: 当我尝试启动空闲实例时,通信通道上的文件结束错误
- sql-server - LDAP / Active Directory : 多个 CN 和 SQL
- python - 列名列表中最大年份和季度的 Python 正则表达式
- r - `testthat::expect_known_value` 的第 3 版替代品是什么?