2016-07-07 39 views
0

我需要生成10到15之間的隨機數字。另外,我需要將這些隨機數字設置爲20到50之間的數字。我想我已經完成了第二部分,我只是不知道該如何放入我的如果聲明條件。有人知道嗎?這裏是我的代碼迄今:如何在一定量之間生成隨機數量的數字?

所有的
#include <iostream> 
#include <time.h> 
#include <stdlib.h> 
using namespace std; 
int main() 
{ 
srand((unsigned)time(0)); 
int random_integer; // Stores random number between 20 and 50 
int random_set; // Stores random amount of numbers 
for(){ // 
    random_integer = 20 + rand()%25; // Random number between 20 and 50 

    cout <<"Generating " << random_set << "random numbers" << random_set " (is a random number between 10 to 15)."; 
    cout << random_integer <<", "; 
    } 

    return 0; 
} 
+0

這是你的答案 - >>>'output = min +(rand()%(int)(max - min + 1))'那麼它是一個複製http://stackoverflow.com/questions/5008804/從範圍生成隨機整數 –

回答

0

首先,這會產生數爲20〜45(不含):

random_integer = 20 + rand() % 25; 

要修復它,用rand() % 30

我需要生成10之間的數字的隨機量至15

然後從0產生10和15以及迭代之間的隨機數(具有環)到該號碼:

int n = 10 + rand() % 5; 
int *numbers = new int[n]; //array that stores the random numbers 
for (int i = 0; i < n; i++) 
    numbers[i] = 20 + rand() % 30; //random number between 20 and 50 
+0

我們還沒有學習過數組。 –

+0

那麼不要使用數組,只要做「int number = 20 + rand()%30;」在循環內部打印出來。 –

0

關鍵是你的模數和你的起始號碼。

// rand() % 5 + 10 has a range of 10 to 10+5 (15) 
// rand() % 30 + 20 has a range of 20 to 20+30 (50) 
int numberCount = rand() % 5 + 10; 
for(int i = 0; i < numberCount; ++i) 
{ 
    int randomNumber = rand() % 30 + 20; 
    cout << randomNumber << endl; 
} 

如果你要包容,使用6和31,而不是5和30

+0

我收到一些奇怪的數字。這是我想要做的:生成11個隨機數(11是10到15之間的隨機數)... ... 11個隨機數在20到50之間:26,23,48,32,44, 21,32,20,49,48,34 –

+0

你得到的奇怪數字是什麼? – rhowen4

1

雖然其他的答案已經介紹瞭如何使用rand(),更好的(和適當的)的方式來產生隨機數來做到這一點在C++中(假設您有一個C++ 11或更高版本的編譯器,您應該有)通過<random>標頭。

這裏是如何在一個給定的範圍內生成隨機int S:

#include <random> 
#include <iostream> 

int main(void) { 
    std::random_device rd; // seed for PRNG 
    std::mt19937 mt_eng(rd()); // mersenne-twister engine initialised with seed 
    const int range_min = 10; // min of random interval 
    const int range_max = 15; // max of random interval 
    // uniform distribution for generating random integers in given range 
    std::uniform_int_distribution<> dist(range_min, range_max); 

    const int n = 10; // number of random int's to generate 
    // call dist(mt_eng) to generate a random int 
    for (int i = 0; i < n; ++i) 
     std::cout << dist(mt_eng) << ' '; 
} 

,當然,你可以通過類似的代碼平凡的隨機化的n值以上爲好。

相關問題