中易网

c语言,文件,请高手帮忙改错。。。

答案:1  悬赏:10  
解决时间 2021-04-28 11:03
  • 提问者网友:冥界祭月
  • 2021-04-27 16:56

题目:创建项目,求1-1000以内的质数并写到文件“file2.out”中。请设计一组测试用例。

程序:#include<stdio.h>
#include<stdlib.h>
int fun (int n)
{int i,j;
 for(i=1;i<=n;i++)
 for(j=1;j<n/2;j++)
 {if((i%j)==0)
 continue;
 return i;
 }
}  
void main()
{FILE *fp;
int k,filename[1000];
printf("please input the name of file:\n");
scanf("%s",filename);
 if(fp=fopen(filename,"w")==NULL)
 {printf("cannot open file");
 exit(0);
 }
 k=fun(1000);
fprintf(fp,"%d",k);
fclose(fp);
}

最佳答案
  • 二级知识专家网友:山鬼偶尔也合群
  • 2021-04-27 18:15

帮你改了程序:


#include<stdio.h>
#include <math.h>
#include<stdlib.h>
void  fun (FILE*fp,int n)
{//是将素数(质数)存入fp中
 int i,j;
 for(i=2;i<=n;i++){
  //找素数
  for(j=2;j<=sqrt(i);j++)
  {
   if(i%j==0)
   break;
  }
  if(j>sqrt(i))fprintf(fp,"%d\n",i);
 }
}  
void main()
{
 FILE *fp;
 char filename[1000];
 printf("please input the name of file:\n");
 scanf("%s",filename);
 if((fp=fopen(filename,"w"))==NULL)
 {
  printf("cannot open file");
  exit(0);
 }
 fun(fp,1000);
 fclose(fp);
}


我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息