简体   繁体   中英

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

I tried reading other questions to find the answer to my question but I got tired of seeing the answer being in a different coding language. I want to change the amount of numbers in my random error code. I am genuinely new to this so please no rude comments.

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

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

I set the array for j to 3 so I could try and get a maximum of 3 numbers.

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

   return 0;
}

Here is where the error comes in, the output of the code only sends the variable address instead of the random number. I really need help with this before I could continue my project. Please help.

Edit: Variable address is "0x7ffc9b46ed5c"

I can assume you want to set an array of size 3 to random numbers.

I set the array for j to 3

j[3] = rand();

You're not doing that, you're setting the 4th element in your array j as a random number, which happens to be out of bounds and invokes undefined behavior.

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

Outputs the address of the first element in array j . Not the whole array.

How i would do it:

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

When you declare an array of size 3 by int j[3] you can refer to the first value by j[0] , second value by j[1] , and the third value by j[2] . If you want to display every value from your array you can use a normal for loop (using j[i]) or a range based for loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM