当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015计算机等级考试四级试题精练(1)
发布时间:2010/11/3 16:23:56 来源:www.xue.net 编辑:城市总裁吧
   初始化
  #include
  #include
  #define MAXNUM 200
  int xx[MAXNUM] ;
  int totNum = 0 ; /* 文件IN.DAT中共有多少个正整数 */
  int totCnt = 0 ; /* 符合条件的正整数的个数 */
  double totPjz = 0.0 ; /* 平均值 */
  int ReadDat(void) ;
  void WriteDat(void) ;
  void CalValue(void)
  {
  }
  void main()
  {
  int i ;
  clrscr() ;
  for(i = 0 ; i < MAXNUM ; i++) xx[i] = 0 ;
  if(ReadDat()) {
  printf(数据文件IN.DAT不能打开!\007\n) ;
  return ;
  }
  CalValue() ;
  printf(文件IN.DAT中共有正整数=%d个\n, totNum) ;
  printf(符合条件的正整数的个数=%d个\n, totCnt) ;
  printf(平均值=%.2lf\n, totPjz) ;
  WriteDat() ;
  }
  int ReadDat(void)
  {
  FILE *fp ;
  int i = 0 ;
  if((fp = fopen(in.dat, r)) == NULL) return 1 ;
  while(!feof(fp)) {
  fscanf(fp, %d,, &xx[i++]) ;
  }
  fclose(fp) ;
  return 0 ;
  }
  void WriteDat(void)
  {
  FILE *fp ;
  fp = fopen(OUT1.DAT, w) ;
  fprintf(fp, %d\n%d\n%.2lf\n, totNum, totCnt, totPjz) ;
  fclose(fp) ;
  }
  A::
  B:EXEC
  C:EXEC SQL
  D:SQL

  题面:
  已知在文件IN.DAT中存有若干个(个数<200)四位数字的正整数, 函数ReadDat( )是读取这若干个正整数并存入数组xx中。请编制函数CalValue( ), 其功能要求: 1. 求出这文件中共有多少个正整数totNum; 2.求出这些数中的各位数字之和是奇数的数的
  个数totCnt, 以及满足此条件的这些数的算术平均值totPjz, 最后调用函数WriteDat()把所求的结果输出到文件OUT1.DAT中。
  注意: 部分源程序存放在PROG1.C中。
  请勿改动主函数main( )、读数据函数ReadDat()和输出数据函数WriteDat()的内容。
  答案:
  #include
  #include
  #define MAXNUM 200
  int xx[MAXNUM] ;
  int totNum = 0 ; /* 文件IN.DAT中共有多少个正整数 */
  int totCnt = 0 ; /* 符合条件的正整数的个数 */
  double totPjz = 0.0 ; /* 平均值 */
  int ReadDat(void) ;
  void WriteDat(void) ;
  void CalValue(void)
  {
  int i, n;
  long cnt = 0 ;
  for(i = 0 ; i < MAXNUM ; i++){
  if(xx[i] > 0){/*是正整数*/
  totNum++ ;/*计数*/
  /*求各位之和*/
  n = xx[i]/1000 + (xx[i]00)/100 + (xx[i]0)/10 + xx[i];
  if( n&1 ){/*是奇数*/
  totCnt++ ;/*统计个数*/
  cnt += xx[i] ;/*计算累加和*/
  }
  }
  }
  totPjz = (double) cnt / totCnt ;/*计算平均值*/
  }
  void main()
  {
  int i ;
  clrscr() ;
  for(i = 0 ; i < MAXNUM ; i++) xx[i] = 0 ;
  if(ReadDat()) {
  printf(数据文件IN.DAT不能打开!\007\n) ;
  return ;
  }
  CalValue() ;
  printf(文件IN.DAT中共有正整数=%d个\n, totNum) ;
  printf(符合条件的正整数的个数=%d个\n, totCnt) ;
  printf(平均值=%.2lf\n, totPjz) ;
  WriteDat() ;
  }
  int ReadDat(void)
  {
  FILE *fp ;
  int i = 0 ;
  if((fp = fopen(in.dat, r)) == NULL) return 1 ;
  while(!feof(fp)) {
  fscanf(fp, %d,, &xx[i++]) ;
  }
  fclose(fp) ;
  return 0 ;
  }
  void WriteDat(void)
  {
  FILE *fp ;
  fp = fopen(OUT1.DAT, w) ;
  fprintf(fp, %d\n%d\n%.2lf\n, totNum, totCnt, totPjz) ;
  fclose(fp) ;
  }
  本题评析:
  这个题目的关键是如何求出一个4位正整数各位时之和,以及如何判断一个正整数是奇数还是偶数。
  对于一个4位正整数x来说,它的千位数=x/1000;
  百位数=(x00)/100;
  十位数=(x0)/10x
  个位数=x。
  判断一个正整数是奇数还是偶数的方法很多,我们这里用的是看它的最低位是0还是1,我们知道:对于一个二进制正整数,它的最低位如果是1,则这个数是奇数;反之,则是偶数。这里我们是将这个正整数和1做“&”(与)运算,即保留这个数的最低位,其余全部清0。
  当然,还一个常见的方法就是让这个数和2做“%”(模)运算。很显然,与运算要优于模运算。
  请参看参考答案及注释。

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved