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

/******************************************************
 功能说明:
 统计给定四位数数组中满足以下条件的个数,并把结果输出到
 文件。千位数数字 + 个位数数字 = 百位数数字 + 十位数数字
 例如:四位数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]);
}


运行结果如下:


猜你喜欢

转载自blog.csdn.net/shb8845369/article/details/12238651