读写文件统计符合要求的四位数

来源:互联网 发布:花生壳教学软件 编辑:程序博客网 时间:2024/05/21 17:02
/****************************************************** 功能说明: 统计给定四位数数组中满足以下条件的个数,并把结果输出到 文件。千位数数字 + 个位数数字 = 百位数数字 + 十位数数字 例如:四位数1425就满足要求,因为 1+5 = 4+2 ******************************************************/#include "stdafx.h"#include <iostream>#include <assert.h>#include <stdlib.h> //产生随机数#include <time.h>   //产生随机数种子using namespace std;const int STARTDIGIT = 2000;const int ARRAYSIZE = 1000;int  input[ARRAYSIZE],output[ARRAYSIZE];int  g_count=0;void InitDataToFile();       //初始化数据到文件void ReadDataFromFile();     //读取文件数据到数组void WriteDataToFile();      //输出数据到文件void GetQualifiedNumber();   //获取满足条件的四位数void BubbleSort();           //对符合条件的四位数进行冒泡排序void PrintToConsole();       //输出结果到控制台int main(int argc, char* argv[]){InitDataToFile();ReadDataFromFile();GetQualifiedNumber();BubbleSort();WriteDataToFile();        PrintToConsole();        system("pause");return 1;}void InitDataToFile(){   FILE *fp;   fp = fopen("G:\IN.txt","w+");   assert(fp!=NULL);   int rand_range_i;   srand((unsigned)time(NULL)); //加上这句,每次初始化的随机数都会不一样   for(int i=0; i<ARRAYSIZE; i++)    {  //产生[STARTDIGIT , STARTDIGIT + ARRAYSIZE)范围的随机数          //系统定义变量 RAND_MAX = 32767   rand_range_i = (double)rand()/(RAND_MAX + ARRAYSIZE +1)*ARRAYSIZE + STARTDIGIT;   fprintf(fp,"%d\n",rand_range_i);   }   fclose(fp);}void ReadDataFromFile(){FILE *fp;fp=fopen("G:\IN.txt","r");assert(fp != NULL);for(int i=0;i<ARRAYSIZE;i++)fscanf(fp,"%d\n",&input[i]);fclose(fp);}void WriteDataToFile(){FILE *fp;fp=fopen("G:\OUT.txt","w");fprintf(fp,"%d\n",g_count);for(int i=0;i<g_count;i++)fprintf(fp,"%d,\n",output[i]);fclose(fp);}void GetQualifiedNumber() {   int i, j;   int temp;   int digit_4,digit_3,digit_2,digit_1;    for(i=0;i<ARRAYSIZE;i++)   {      digit_4= input[i]/1000;     //千位数数字      digit_3= input[i]%1000/100; //百位数数字      digit_2= input[i]%100/10;   //十位数数字      digit_1= input[i]%10;       //个位数数字      if((digit_4+digit_1) == (digit_3+digit_2))      {      output[g_count++]=input[i];      }   }}void BubbleSort(){int i,j,temp;  for(i=0;i<g_count-1;i++)  for(j=0;j<g_count-1-i;j++)  {if(output[j]>output[j+1]) {  temp=output[j];  output[j]=output[j+1];  output[j+1]=temp;}  }}void PrintToConsole() {    printf("cnt=%d\n",g_count);    for(int i=0;i<g_count;i++)       printf("b[%d]=%d\n",i,output[i]);}

 

运行结果如下: