c语言如何从文件读取所有整数并写出质数与所有数的比值
答案:1 悬赏:70
解决时间 2021-11-14 22:57
- 提问者网友:前事回音
- 2021-11-14 03:27
c语言如何从文件读取所有整数并写出质数与所有数的比值
最佳答案
- 二级知识专家网友:花一样艳美的陌生人
- 2021-11-14 04:41
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "stdlib.h"
int prime(int n){
int i;
if(n>2 && !(n&1) || n<2)
return 0;
for(i=3; i*i<=n;i+=2)
if(!(n%i))
return 0;
return 1;
}
int main(void){
FILE *fp;
int np,n,x;
if((fp=fopen("123.txt","r"))==NULL){
printf("Open the file failure...\n");
exit(0);
}
np=n=0;
while(fscanf(fp,"%d",&x)>0){
n++;
if(prime(x))
np++;
}
fclose(fp);
printf("The result is %d:%d\n",np,n);
return 0;
}
#include "stdio.h"
#include "stdlib.h"
int prime(int n){
int i;
if(n>2 && !(n&1) || n<2)
return 0;
for(i=3; i*i<=n;i+=2)
if(!(n%i))
return 0;
return 1;
}
int main(void){
FILE *fp;
int np,n,x;
if((fp=fopen("123.txt","r"))==NULL){
printf("Open the file failure...\n");
exit(0);
}
np=n=0;
while(fscanf(fp,"%d",&x)>0){
n++;
if(prime(x))
np++;
}
fclose(fp);
printf("The result is %d:%d\n",np,n);
return 0;
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯