It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我编写了以下代码以在C中生成随机数。

int main (int argc, char *argv[])
{
    unsigned int iseed = (unsigned int)time(NULL);
    srand (iseed);

    /* Generate random number*/
    int i;
    for (i = 0; i < 1; i++)
    {
        printf ("Random[%d]= %u\n", i, rand ());
    }
    return 0;
}


输出给我一个10位数的随机数,如何更改输出中打印的位数?

最佳答案

rand()为您提供一个介于0和RAND_MAX之间的数字,该数字可能很大。

如果要在[0, N)范围内获得均匀样本,则需要将范围划分为多个区域:

int my_max = (RAND_MAX / N) * N;

int result;

while ((result = rand()) >= my_max) { } // #1

return result % N;


#1行中的条件很少会得到满足,但是如果结果不在N的倍数范围内,我们需要重新滚动,以免偏向于高结果。

关于c - C随机数生成器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12400320/

10-13 02:44