0

Im trying to make code that stores random double numbers from interval (0 to 1) excluding 0 and 1.

So far i made this but it apparently is for interval from 0 to 1 including 0 and 1. That IF condition is there because i didn't know how to exclude the 1 and 0 so the cycle goes back by 1 to generate new number.

How can i modify this function to correctly generate from said interval? We dont use C++ 11 at school so please just tell me how to modify the generating line. generating seed is at the main function.

This program works but the teacher specifically asked us to generate from (0,1) otherwise -points

void init(double *A, const int N)
{  
    double p;

    for(int i=0; i<N; ++i)
    {
        //  p = (((double)rand() / RAND_MAX) + 1) / (((double)(RAND_MAX))+2);
        p = (double)rand() / RAND_MAX;
        if(p == 0 || p == 1)
        {
            i--;
            continue;
        }
        else A[i]= p;
    }
}
He4moud
  • 1
  • 1
  • "We dont use C++ 11 at school" - what? why? – asu Nov 06 '16 at 18:18
  • yes it works but the problem is it doesn't work like the Teacher wants to. He gives -points for not writing it exactly how it is asked in the homework. I have to make it that at the generating line it will generate from (0,1) not from [0,1] and then exclude 0 or 1 and repeat the process. – He4moud Nov 06 '16 at 18:19
  • 1
    There's always `(rand()+1.0)/(RAND_MAX+2.0)`. – David Schwartz Nov 06 '16 at 18:22
  • @David for homework questions it's better to *guide* someone to the answer rather than just blurt it out. – Mark Ransom Nov 06 '16 at 18:29
  • Problem seems to be fixed thanks to @David Schwartz however i still dont really understand why it does. – He4moud Nov 06 '16 at 18:33
  • @He4moud: Please note that there are implicit type casts in the comment of DavidSchwartz and that those type casts are important. Just saying, because it is easy to overlook. `RAND_MAX` might be equal to the largest integer of the return type of rand(). Adding any positive number would result in an overflow. Because he writes `2.0` instead of `2`, the left argument of `+` is converted to a double. – Markus Mayr Nov 06 '16 at 18:44
  • @He4moud - Why did you close this question? I was just about to give you the best hint of all time. – selbie Nov 06 '16 at 19:45
  • Please re-open if you want a good hint. – selbie Nov 06 '16 at 19:47

0 Answers0