c语言用fprintf输出一维数组

2024-12-14 09:50:00
推荐回答(2个)
回答1:

你好!!

随机数写入文件的时候,也要采用循环写入,你看看吧

程序的增加部分是,循环写入;

	for(i=0;i<=9;i++)
{
fprintf(out,"%d  ",p[i]);
}

下面是完整的代码

#include
#include
int a,b,p[9],i;
FILE *in,*out;
int main()
{
unsigned int seed;
in=fopen("D:\\input.txt","r");
fscanf(in,"%d,%d",&a,&b);
seed=a;
srand(seed);

for(i=0;i<=9;i++)
{
p[i]=rand()%(b-a)+a;
printf("%d ",p[i]);

}

    out=fopen("D:\\output.txt","w");
fprintf(out,"随机数列为 ");

for(i=0;i<=9;i++)
{
fprintf(out,"%d  ",p[i]);
}
}

回答2:

改如下,对照看——

void main(){
unsigned int seed;
in=fopen("D:\\input.txt","r");
fscanf(in,"%d,%d",&a,&b);
seed=a;
srand(seed);
out=fopen("D:\\output.txt","w");
for(i=0;i<=9;i++){
p[i]=rand()%(b-a)+a;
printf("%d ",p[i]);
fprintf(out,"%d ",p[i]);
}
}