题目:创建项目,求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);
}
帮你改了程序:
#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);
}
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!