[英]C++ Random Number Generator in Array
我想用C ++編寫一個程序,該程序會顯示1到54之間的6個隨機數。在下面可以找到代碼。 出於某些奇怪的原因,當我運行程序時,有時會偶然發現如下輸出:
Bugunku sansli loto sayiniz:17 1 12 32 33 3418568
我不知道為什么最后一個數字會忽略我的規則。 任何幫助,將不勝感激。
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 6; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
我不知道為什么最后一個數字會忽略我的規則。
因為在for
循環中訪問的最后一個數字超出了數組的范圍,所以對其取消引用將導致UB。 for
循環應為
for (int i = 0; i < 5; i++)
~
然后i
將是0
〜 4
,循環5次,而不是6倍,如圖您的代碼。
您可以使用基於范圍的for循環 (自C ++ 11起)來避免此類錯誤:
for (auto& i : myArray) {
i = (rand() % 55) + 1;
cout << i << '\t';
}
從1到54的隨機數
因此,這也是不正確的: (rand() % 55) + 1;
您將需要(rand() % 54) + 1;
因為您上次去過myArray [5] ,而您的數組沒有這個地方,所以您知道了
您需要這樣寫:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 5; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
如果要6個項目,則需要為6個項目制作一個數組
int myArray[5];
這將提供5個項目,其中
int myArray[6];
這將為您提供6個項目,這將解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.