一、题目要求
已知数据文件in.dat中存有300个四位数,并调用读函数readDat()把这些数存入数组a中,请编制一函数jsValue(),其功能是:求出所有这些四位数是素数的个数cnt,再求出所有满足此条件的四位数平均值pjz1,以及所有不满足此条件的四位数平均数pjz2。最后main()函数调用写函数把结果cnt,pjz1,pjz2,输出到out.dat文件中
二、in.dat文件内容
7704,9774,3213,5845,7703,2902,1925,2584,7429,6646 3793,8640,4364,3032,9190,2498,6394,3796,2434,6791 5552,9052,9159,8245,7965,1071,8157,6526,2164,6767 4853,1174,4564,5427,7279,9832,3640,7897,3211,4788 6556,4781,2168,6014,7795,6536,9461,4287,8029,8303 2609,8795,8386,3911,8130,7268,1906,7345,3678,5823 8074,6963,7874,6066,4509,8976,1740,2026,7047,4730 9538,2193,8473,6729,4207,5095,4623,4933,6226,8098 1277,5480,1906,4109,9047,1986,5882,8444,1029,6515 2612,7297,6934,8495,7731,1625,1305,7953,7385,3620 7206,4549,5736,3131,6875,6917,6087,4640,5314,8646 6077,5677,7345,4143,1513,8101,2038,9879,3946,6643 7763,6108,4788,9055,8186,5416,5699,6733,5416,2320 2430,4772,9962,9676,1319,7767,7369,1411,3663,2876 2245,4810,5400,6045,1504,4178,7264,2763,7050,1490 8790,4014,9280,7105,7113,3600,8221,8203,6127,7313 1850,5983,9689,4102,1036,6375,5064,7188,9887,9800 6871,4856,2432,9562,3426,9013,5104,4724,4785,9953 5939,6668,8700,4730,9737,4055,6544,9763,1034,2855 8078,5111,4817,4593,9876,1189,2507,1197,1782,4347 7961,8612,9699,6108,4221,2489,8895,3672,8226,8724 6302,7624,7506,8568,4013,2785,3528,6712,1155,3150 1388,5803,6328,6841,5825,7802,2022,6290,1775,3652 9699,6573,8082,9016,4369,4002,3205,2688,8414,7572 2830,1231,3888,5137,5555,8976,2543,6542,8986,5921 5346,1368,2566,3304,4089,3880,1244,6650,6523,6123 1243,7488,5262,9992,3115,9270,6989,1595,1283,2645 4075,9471,7983,9093,7642,8847,5686,4168,8550,8941 5188,2290,3219,2853,6978,9053,5843,7153,6382,6289 3022,5591,9981,7296,2421,7328,9575,7586,1190,8504
三、程序代码
#include <stdio.h> int a[300], cnt=0; double pjz1=0.0, pjz2=0.0; //从in.dat中读取文件内容 void readDat() { FILE *fp; int i; fp = fopen("in.dat","r"); for(i = 0; i < 300; i++) { fscanf(fp, "%d,", &a[i]); } fclose(fp); } //把运行结果输出到out.dat文件中 void writeDat() { FILE *fp; fp = fopen("out.dat","w"); fprintf(fp, "%d\n%7.2lf\n%7.2lf\n", cnt, pjz1, pjz2); fclose(fp); } //判断是否是素数 int isP(int m) { int i; for(i = 2; i < m; i++) { if(m % i == 0) { return 0; } } return 1; } void jsValue() { int i=0,flag; int j=0,k=0; int sList[300]; //存放素数的数组 int nsList[300]; //存放非素数的数组 for(i=0;i<300;i++) { flag=isP(a[i]); if(flag) { cnt++; sList[j++]=a[i]; } else { nsList[k++]=a[i]; } } for(i=0;i<j;i++) { pjz1+=sList[i]; } for(i=0;i<k;i++) { pjz2+=nsList[i]; } pjz1/=j; pjz2/=k; } main() { readDat(); jsValue(); writeDat(); printf("cnt=%d\n满足条件的平均值pzj1=%7.2lf\n不满足条件的平均值pzj2=%7.2lf\n", cnt,pjz1,pjz2); }
四、程序运行结果
原文地址:https://www.cnblogs.com/wutao666/p/9589119.html
时间: 2024-10-06 05:53:14