Question:

Random Negative Numbers in C

by  |  earlier

0 LIKES UnLike

I have to write a program in C that generates two random numbers from -1000 to 1000 so I can add them

so an example would be

(-)541 <----- random

241 <----- random

---------

? <----- ask user for the answer

 Tags:

   Report

4 ANSWERS


  1. int n = random(1001);

    int mod = random(2);

    if(mod = 0){

    n = n * -1;

    }

    return n;


  2. What are you asking? HOW to generate the random numbers?

  3. you can use rand or srand (from stdlib)

    eg.

    #include &lt;stdlib.h&gt;

    #define ASEED 12346653

    int getnum()

    {

        return (int)( (double)srand(ASEED) / (double)RAND_MAX * 2000.0 - 1000.0 );

    }

    srand generate a pseudo rand num between 0 and RAND_MAX, then you obtain a number between 0.0 and 1.0, multiply by 2000 -&gt; number from 0 to 2000, subtract 1000 to obtain a number between -1000.0 and 1000.0, make it integer...

    hope it&#039;s right


  4. To generate a random number from -1000 to 1000 (I&#039;m assuming you mean inclusive, so -1000 and 1000 are possible outputs), you need to follow two steps:

    1) Figure out how many possible outputs there are. In this case, there are 2,001 possible outputs. (-1 to -1000 is 1,000, 1 to 1,000 is another 1,000, and zero makes 2,001.)

    2) Figure out how to get from zero to your lowest possible answer. Which is simple, subtract 1,000.

    So the finished code would be:

    i=(rand%2001)-1000;

    Some older random number generators may produce biased output in their lower order bits. If you&#039;re really picky, you can use:

    i=(int)(2001.0 * (rand()/(RAND_MAX+1.0)))-1000;

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.