生成一组随机数

时间:2015-11-08 09:45:33

标签: c random file-handling

问题陈述:创建三个输入文件:INPUT01.DAT,INPUT02.DAT,INPUT03.DAT,每个都有100个随机数。 从每个输入文件中读取,并在两个文件中输出奇数和偶数:ODD.TXT,EVEN.TXT,提及源文件的名称。

int main()

{
    FILE *fp1,*fp2,*fp3,*g,*h;
    srand((unsigned) time(NULL));

    int i, noofr, j ,k,l,num[110];
    g= fopen("EVENq13.TXT","a+");
    h= fopen("ODDq13.TXT","a+");


    printf ( "Enter number of records: " ) ;
    scanf ( "%d", &noofr ) ;
    fp1= fopen ( "INPUT01.TXT", "w+" ) ;
    fp2= fopen ( "INPUT02.TXT", "w+" ) ;
    fp3= fopen ( "INPUT03.TXT", "w+" ) ;
    if ( fp1 == NULL||fp2==NULL||fp3==NULL )
    {
        printf ( "Unable to create file." ) ;
        getch( ) ;
        exit ( 0 ) ;
    }

    for ( i = 0 ; i < noofr ; i++ )
    {
        j = rand() % 100 + 1;         
        fprintf(fp1,"%d\t",j);
    }

    for ( i = 0 ; i < noofr ; i++ )
    {
         k= rand() % 100 + 1;
        fprintf(fp2,"%d\t",j);
    }

    for ( i = 0 ; i < noofr ; i++ )
    {   l= rand() % 100 + 1;
         fprintf(fp3,"%d\t",j);
    }

    fclose ( fp1 ) ;
     fclose ( fp2) ;
      fclose ( fp3 ) ;

    fp1 = fopen ( "INPUT01.TXT", "r" ) ;
    fp2 = fopen ( "INPUT02.TXT", "r" ) ;
    fp3 = fopen ( "INPUT03.TXT", "r" ) ;

    fprintf(g,"\n\n Nos from INPUT01 \n");
   fprintf(h,"\n\n Nos from INPUT01 \n");

    for(i=0;i<noofr;i++)
    {fscanf(fp1,"%d ",&num[i]);
     if (num[i]%2==0)
     {
        fprintf(g,"%d\t",num[i]);
     }
     else
     {
        fprintf(h,"%d\t",num[i]);
     }
    }


    fprintf(g,"\n\n Nos from INPUT02 \n");
    fprintf(h,"\n\n Nos from INPUT02 \n");


    for(i=0;i<noofr;i++)
    {fscanf(fp2,"%d ",&num[i]);
     if (num[i]%2==0)
     {
        fprintf(g,"%d\t",num[i]);
     }
     else
     {
        fprintf(h,"%d\t",num[i]);
     }
    }
    fprintf(g,"\n\n Nos from INPUT03 \n");
    fprintf(h,"\n\n Nos from INPUT03 \n");


    for(i=0;i<noofr;i++)
    {fscanf(fp3,"%d ",&num[i]);
     if (num[i]%2==0)
     {
        fprintf(g,"%d\t",num[i]);
     }
     else
     {
        fprintf(h,"%d\t",num[i]);
     }
    }




    fclose ( fp1 ) ;
     fclose ( fp2) ;
      fclose ( fp3 ) ;
    fclose(g);
    fclose(h);
    printf ( "\nFile is created. \nPress any key to continue." ) ;
    getch();
}

第二组和第三组数字变为常数而不是随机数,常数通常是第一组数字的最后一个数字。

我知道我在设定种子时出错了。是否有可能纠正这一点。

1 个答案:

答案 0 :(得分:1)

更改您的第二个和第三个fprintf()调用以引用正确的变量。换句话说,从中:

fprintf(fp2,"%d\t",j);

到此:

fprintf(fp2,"%d\t",k);

从此:

fprintf(fp3,"%d\t",j);

到此:

fprintf(fp3,"%d\t",l);