【问题标题】:Generate unique multiple random numbers生成唯一的多个随机数
【发布时间】:2023-03-16 22:32:01
【问题描述】:

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

问题是当我使用代码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.contains(randomNb) 替换为对该函数的调用。你有什么理由不能自己写那个函数吗?这就是你寻求帮助的原因吗?
  • 哦对不起,我已经编辑了我的问题^^
  • results.contains(randomNb) 不是合法的 C++。那不可能是你的代码。
  • 它不起作用,这就是问题所在!为什么我应该正确??

标签: c++ arrays qt random


【解决方案1】:

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++;
    }
}

【讨论】:

  • 抱歉,我在 qt 和 C++ 方面是一个非常糟糕的初学者,你能在我的代码中写这个吗?谢谢!
  • @RochesterFox 另请注意代码中的非一错误。我再次更新了答案。
  • 阅读文档doc.qt.digia.com/qt/qlistview.html。如果您无法弄清楚,请发布一个新问题。不过也不是很困难。只需花点时间就可以了 :-)
猜你喜欢
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
相关资源
最近更新 更多