C语言每日一练——第4题
一、题目要求
已知数据文件in.dat中有300个四位数,并调用readDat()函数把这些数存储数组a中,编写函数jsValue(),其功能是:求出所有这些四位数是素数的个数cnt,再把所有满足此条件的四位数依次存入数组b中,然后对数组b的按从小到大顺序排列,最后编写函数wirteDat()把数组b中的数输出到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], b[300], cnt=0; void readDat() { FILE *fp; int i; fp = fopen("in.dat","r"); for(i = 0; i < 300; i++) { fscanf(fp, "%d,", &a[i]); } fclose(fp); } void writeDat() { FILE *fp; int i; fp = fopen("out.dat","w"); fprintf(fp, "%d\n", cnt); for(i = 0; i < cnt; i++) { fprintf(fp, "%d\n", b[i]); } 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,j; int temp; for(i=0;i<300;i++) { if(isP(a[i])) { b[cnt++]=a[i]; } } //方法一:冒泡排序 for(i=0;i<cnt;i++) { for(j=0;j<cnt-i-1;j++) { if(b[j]>b[j+1]) { temp=b[j]; b[j]=b[j+1]; b[j+1]=temp; } } } //方法二: /*for(i = 0; i < cnt; i++) { for(j = i + 1; j < cnt; j++) { if(b[i] > b[j]) { temp = b[j]; b[j] = b[i]; b[i] = temp; } } }*/ } void main() { int i; readDat(); jsValue(); writeDat(); printf("cnt=%d\n", cnt); for(i = 0; i < cnt; i++) { printf("b[%d]=%d\n", i, b[i]); } }
四、程序运行结果