首页 > 技术文章 > C生成随机数,奇葩问题

fangying7 2013-12-13 21:26 原文

今天需要生成一个随机数,奇怪的问题发生了。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MSG_LEN 2610

int main(int argc,char **argv)
{
    FILE *fp = NULL;
    char msg_bit;
    int i = 0;

    char comma = ',';

    if((fp = fopen("msg.txt","w+")) == NULL)
    {
        printf("Error can't open file!\n");
        return -1;
    }
    
    
    for(i = 0; i<= MSG_LEN;i++ )
    {
        srand((unsigned )time(NULL));
        msg_bit = rand()%2; 
        fputc(msg_bit + '0',fp);
        fputc(comma,fp);
    }
        
    fclose(fp);

    return 1;
}

输出的全是 0,根本不是随机数。。。。。。!!!!编译环境是gcc 4.7

把其中的srand那句干掉反而就可以了,,,,,无语。难道C语言已经自动改进了随机数生成了,我真是吃力不讨好。。。。

推荐阅读