簡體   English   中英

如何在 C++ 的代碼中指定隨機數的數量

[英]How do I specify the amount of random numbers in my code in C++

我嘗試閱讀其他問題以找到我的問題的答案,但我厭倦了看到答案使用不同的編碼語言。 我想更改隨機錯誤代碼中的數字數量。 我對此真的很陌生,所以請不要粗魯的評論。

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;
 
int main () {
   int i,j[3];
 
   
   srand( (unsigned)time( NULL ) );

我將 j 的數組設置為 3,這樣我就可以嘗試獲得最多 3 個數字。

for( i = 0; i < 1; i++ ) {
      
      j[3] = rand();
      cout <<"Error code: " << j << endl;
   }

   return 0;
}

這里是錯誤出現的地方,代碼的 output 只發送變量地址而不是隨機數。 在繼續我的項目之前,我真的需要幫助。 請幫忙。

編輯:變量地址是“0x7ffc9b46ed5c”

我可以假設您想將大小為 3 的數組設置為隨機數。

我將 j 的數組設置為 3

j[3] = rand();

您沒有這樣做,您將數組j中的第 4 個元素設置為隨機數,這恰好超出范圍並調用未定義的行為。

cout <<"Error code: " << j << endl;

輸出數組j中第一個元素的地址。 不是整個數組。

我會怎么做:

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
  srand(time(NULL));
  int j[3];
  for (int i = 0; i < 3; ++i)
    j[i] = rand(); //sets every index of the array to rand()
  cout << "Error code: ";
  for (int i = 0; i < 3; ++i)
    cout << j[i] << '\n'; //outputs all values from the array

  return 0;
}

當您通過int j[3]聲明大小為 3 的數組時,您可以通過j[0]引用第一個值,通過j[1]引用第二個值,通過j[2]引用第三個值。 如果要顯示數組中的每個值,可以使用普通的 for 循環(使用 j[i])或基於范圍的 for 循環:

for(int& i : j)
    cout<<i; //this loop will display every component from your array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM