gpt4 book ai didi

c++ - 生成唯一的多个随机数

转载 作者:行者123 更新时间:2023-11-28 07:54:24 25 4
gpt4 key购买 nike

我想生成唯一的随机数并根据这些随机数添加项目。这是我的代码:

问题是当我使用代码 results.contains(randomNb) 验证生成的数字是否存在于数组中时:

   int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 1;
int results[1000];
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results[i] = randomNb;
//We add the new randomNb in the array
i++;
}
}

最佳答案

results 是一个数组。这是一个内置的 C++ 类型。它不是类类型,也没有方法。所以这行不通:

results.contains(randomNb)

您可能想改用 QList。喜欢:

QList<int> results;

向其中添加元素:

results << randomNb;

此外,您的代码中有一个差一错误。您从 1 (i = 1) 而不是 0 开始计数。这将导致漏掉最后一个数字。您应该将 i 初始化更改为:

int i = 0;

随着更改,您的代码将变为:

int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 0;
QList<int> results;
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results << randomNb;
//We add the new randomNb in the array
i++;
}
}

关于c++ - 生成唯一的多个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13077356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com