简体   繁体   中英

undefined behaviour of srand and rand

I am trying to generate random number using srand and rand . Here I want to generate specific number of digit. When I am executing my program at some time if I ask to generate 5 digit number number it is not giving me desired output.

My code is

for(k=0;k<n;k++)
    {
            temp = temp*10;
    }
    srand(time(NULL));
    i = rand()%temp;
    printf("%d\n",i);
    k = 0;
    temp = n;
    while(i != 0)
    {
            arr1[n+k] = i%10;
            i = i/10;
            n--;
    }

Output

Number of digits you want : 5
2031
while loop 1
while loop 3
while loop 0
while loop 2
N is 1
arr1[1] = 10651312
arr1[2] = 2
arr1[3] = 0
arr1[4] = 3
arr1[5] = 1

tell me where is the problem for getting desired number of digits.

Edit I run that code around 100 times and out of those four time it is not working, rest is fine...

The problem is you're looping on the size of the random number you've generated and not the size of the array. In your example you want five digits but your code has generated a four digit number, 2031. This means that in the iteration of your bottom loop

  • ... n = 2, i = 2: store a[2] = 2, i = 0
  • ... n = 1, i = 0: loop condition failed, a[1] never set

which leaves random garbage in a[1]. If your random number did in fact contain 5 digits, not 4, then it would have completed the loop correctly.

Instead you want to loop over n

for(int j = n; j > 0; --j)
{
    arr1[n+j] = i%10;
    i = i/10;
}

Note that this is still using the array as 1-based, whereas in c arrays are 0-based, ie they start at element 0, ie in order to use arr1[5] you need to have malloced or declared 6 array elements or 6*sizeof(int) bytes. Also note that you should use better variable names than temp , and there's no benefit to reusing the variable: your compiler will automatically reuse registers and sort that out for you.

There are several problems here.

First, call srand() once before actually producing random numbers.

Second, your method taking the returned number modulo some power of 10 will, of course, also return numbers that are lower. For example, n%100000 could be anything from 0 to 99999.

n = rand() % (largest - smallest + 1) + smallest;

If you want a 5 digit number, what is the smallest 5 digit number? Do the same for the largest number. That can be used for any number range with no need to fill an array or anything.

Now you just need to figure out how to generate the largest and smallest values for the number of digits specified.

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM