2012-10-25 183 views
0

我想生成唯一的随机数并添加这些随机数的函数。这是我的代码:生成唯一的多个随机数

问题是,当我确认如果阵列中存在具有代码生成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++; 
     } 
    } 
+0

...和你的问题是......什么? –

+0

你似乎离工作解决方案只有一步之遥。所有你需要的是一个函数,检查一个特定的数字是否在一个数组(特定的大小)。然后你可以用一个对该函数的调用来替换'results.contains(randomNb)'。你有什么理由不能自己写这个函数吗?这是你要求的帮助吗? – john

+0

对不起,我编辑了我的问题^^ – Random78952

回答

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

对不起,但我是一个非常糟糕的在qt和C++的begeigner,你可以在我的代码中写这个吗?谢谢 ! – Random78952

+0

@RochesterFox我已经更新了答案。 –

+0

非常感谢!这是工作 ! – Random78952