Search code examples
c++randomsrand

rand from -30 to 30


Hello I want print numbers from 30 to -30, this is my code

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

int main(){

   srand(time(0));
   int arr[20] = {0};
   for(int i = 0; i < 20; i++){    
      arr[i] = rand() % 30+(-30);
   }
   for(int i = 0; i < 20; i++){
      cout << arr[i] << " "<<endl;
   }
   return 0;
}

I'm not know why, but all numbers are negative ?


Solution

  • You got a problem in your logic ... You generate numbers from 0-30 and then subtract 30 ... The maximum number you can get is 0...

    arr[i] = (rand() % 61) - 30;

    gives you what you want