1. 程式人生 > >隨機數生成並寫入檔案(C實現)

隨機數生成並寫入檔案(C實現)

#include <stdlib.h>  
#include <stdio.h>  
#include <time.h>  
  
//生成隨機數列  
int write()  
{  
    int i,j;  
    FILE *pf = NULL;  
    int a1[50],a2[50];  
    srand((unsigned)time(NULL));//隨機種子  
    pf = fopen("C:\\Users\\Administrator\\Desktop\\data.txt","a");  
    //生成數列  
    for(i=0; i<50; i++)  
    {  
        a1[i] = 1+(int)(5399.0*rand()/(RAND_MAX+1.0));
        a2[i] = 1+(int)(5.0*rand()/(RAND_MAX+1.0));
    }  
    //格式化輸出到檔案中  
    for(i=0; i<47; i++)  
    {  
    		
            fprintf(pf,"%-5d",a1[i+j]);  
            fprintf(pf,"%-5d",a2[i+j]);
        	fprintf(pf,"\n");  
    }  
    fclose(pf);  
    return 0;  
}  
int read()  
{  
    int i,j;  
    FILE *pf;  
    int arr[2000];  
    if((pf = fopen("sort.txt","r"))==NULL)  
    {  
        printf("Error\n");  
        system("PAUSE");  
        exit(1);  
    }  
    //讀取檔案內容到數列  
    for(i=0; i<200; i++)  
    {  
        for(j=0; j<10; j++)  
        {  
            fscanf(pf,"%d",&arr[i*10+j]);  
        }  
        fscanf(pf,"\n");  
    }  
    fclose(pf);  
    //將數列輸出到螢幕  
    for(i=0; i<200; i++)  
    {  
        for(j=0; j<10; j++)  
        {  
            printf("%-5d",arr[i*10+j]);  
        }  
        printf("\n");  
    }  
  
    return 0;  
}  

int main(){
	
	write();
	
	return 0;
}