Talal02
Talal02

Reputation: 162

Working of rand() function in particular question?

The range of the function is from 0 - 32767. We have to generate random numbers between this range and calculate the average of each number generated it would be exactly equal to 16383.5. And in this problem, we are required to find the smallest number of time Rand() function is called to produce average = 16383.5+-0.0001.

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

int main()
{
    double x,avg = 0,n=1;
    while(n<=1000){
          x = (rand() % (32767 + 1 ) + 0) ;
          avg = x/n;
          if((avg == (16383.5+0.0001))||(avg == (16383.5-0.0001))){
          break;
          }
          n++;
    }
    cout<<n<<endl<<y<<endl;
}

It must print n as it can but I am not getting required ans. as avg never reaches that value. But why?

Upvotes: 0

Views: 108

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

Your original post didn't compute any average because it didn't tally any sum to divide by n. No sum = no average computation. Further, your expression for break-checking is wrong. It's looking for exact matches of two values, your assignment is to wait until the result is within a range of 16383.5 +/- 0.0001. Finally, a minor point, you never seeded rand, so don't expect anything but the same answer repeatedly.

Doing this right (enough), is below:

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

int main()
{
    std::srand(static_cast<unsigned>(std::time(nullptr)));

    double sum = 0;
    int n = 1;
    for (;; ++n)
    {
        double x = std::rand() % 32768;
        sum += x;
        double avg = sum / n;
        if ((avg <= 16385.5 + 0.0001) && (avg >= 16383.5 - 0.0001))
            break;
    }
    std::cout << n << '\n';
}

Sample Output

351

Upvotes: 1

Related Questions