Negative Random Numbers

Puckdropper 0 Tallied Votes 244 Views Share

So you want random numbers with negative values... How do you get them? This is a simple method to do so.

#include <iostream>
#include <time.h>

using namespace std;

/* define number of elements in the array */
const int NumElements = 16383;
const int Range = 33766;

int RandNums[NumElements]; // An array of elements to hold random numbers

main()
{
	/* initialize random generator */
  srand ( time(NULL) );
	int count; //declare count before it can be used
	for(count = 0; count < (NumElements - 1); count++)
    {

  	/* Assign a value to the array */
		RandNums[count] = rand()%Range;
		if (RandNums[count] > Range/2)
		  {
			//If the value is greater than the cut off point, subtract it from the cut-off point and multiply by negative 1.
			RandNums[count] = RandNums[count] - 16383;
			RandNums[count] = RandNums[count] * -1;
			}
		/* Print results */
		cout << RandNums[count] << endl;
	  }
	return 0;
}
manutd 2 Junior Poster

Main should have a type int main (void)

todd.sifleet 0 Newbie Poster

This is terrible code, why would you make this simple task so complicated....just create a random number...half the time multiply by negative 1(choose this randomly)...that way your range doesn't shrink and you get a perfectly uniform distribution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.