3.已知在文件IN11.DAT中存有若干個(個數<200)4位數字的正整數,函數ReadDat() 的功能是讀取這若干個正整數并存入數組xx中。請編制函數CalValue(),其功能要求:(1)求出該文件中共有多少個正整數totNum;(2)求這些數右移1位后,產生的新數是偶數的數的個數totCnt,以及滿足此條件的這些數(右移前的值)的算術平均值totPjz,最后調用函數WriteDat()把所求的結果輸出到文件OUT11.DAT中。
注意:部分源程序已給出。
請勿改動主函數main()、讀函數ReadDat()和寫函數WriteDat()的內容。
#include
#include
#define MAXNUM 200
int xx[MAXNUM] ;
int totNum = 0 ; /* 文件IN11.DAT中共有多少個正整數 */
int totCnt = 0 ; /* 符合條件的正整數的個數 */
double totPjz = 0.0 ; /* 平均值 */
int ReadDat(void) ;
void Writedat(void) ;
void CalValue(void)
{
int i; /*定義循環控制變量*/
int data; /*用于保存處理后產生的新數*/
for(i=0;i<200;i++) /*逐個取數組xx中的數進行統計*/
if(xx[i]>0) /*判斷是否正整數*/
{
totNum++; /*統計正整數的個數*/
data=xx[i]>>1; /*將數右移一位*/
if(data%2==0) /*如果產生的新數是偶數*/
{
totCnt++; /*統計這些數的個數*/
totPjz+=xx[i]; /*并將滿足條件的原數求和*/
}
}
totPjz/=totCnt; /*求滿足條件的這些數(右移前的值)的算術平均值*/
}
void main()
{
int i ;
system("CLS");
for(i = 0 ; i < MAXNUM ; i++)
xx[i] = 0 ;
if (ReadDat ())
{
printf("數據文件IN11.DAT不能打開!\007\n");
return ;
}
CalValue() ;
printf("文件IN11.DAT中共有正整數= %d 個\n", totNum);
printf("符合條件的正整數的個數= %d 個\n", totCnt);
printf("平均值=%.2lf\n", totPjz);
Writedat() ;
}
int ReadDat(void)
{
FILE *fp;
int i = 0 ;
if((fp = fopen ("IN11.DAT", "r")) == NULL)
return 1 ;
while(! feof(fp))
{
fscanf(fp, "%d,", &xx[i++]) ;
}
fclose(fp) ;
return 0 ;
}
void Writedat(void)
{
FILE *fp;
fp = fopen("OUT11.DAT", "w") ;
fprintf(fp, "%d\n%d\n%.2lf\n", totNum, totCnt, totPjz) ;
fclose(fp) ;
}
4.已知數據文件IN12.DAT中存有300個4位數,并已調用讀函數readDat()把這些數存入數組a中。請編制函數jsValue(),其功能是:求出千位數上的數加個位數上的數等于百位數上的數加十位數上的數的個數cnt,再把所有滿足此條件的4位數依次存入數組b中,然后對數組b的4位數按從小到大的順序進行排序,最后調用寫函數writeDat()把數組b中的數輸出到OUT12.DAT文件中。
例如:6712,6+2=7+1,則該數滿足條件,存入數組b中,且個數cnt=cnt+1。
8129,8+9≠1+2,則該數不滿足條件,忽略。
注意:部分源程序已給出。
程序中已定義數組:a[300],b[300],已定義變量:cnt。
請勿改動主函數main()、讀函數readDat()和寫函數writeDat()的內容。
#include
int a[300], b[300], cnt=0;
void readDat();
void writeDat();
void jsValue()
{
int i,j; /*定義循環控制變量*/
int a1,a2,a3,a4; /*定義變量保存4位數的每位數字*/
int temp; /*定義數據交換時的暫存變量*/
for(i=0;i<300;i++) /*逐個取每一個4位數*/
{
a4=a[i]/1000; /*求4位數的千位數字*/
a3=a[i]%1000/100; /*求4位數的百位數字*/
a2=a[i]%100/10; /*求4位數的十位數字*/
a1=a[i]%10; /*求4位數的個位數字*/
if(a4+a1==a3+a2) /*如果千位數加個位數等于百位數加十位數*/
{
b[cnt]=a[i]; /*將滿足條件的數存入數組b中*/
cnt++; /*統計滿足條件的數的個數cnt*/
}
}
for(i=0;i
for(j=i+1;j
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
}
void main()
{
int i;
readDat();
jsValue();
writeDat();
printf("cnt=%d\n", cnt);
for(i=0; i
printf("b[%d]=%d\n", i, b[i]);
}
void readDat()
{
FILE *fp;
int i;
fp = fopen("IN12.DAT", "r");
for(i=0; i<300; i++)
fscanf(fp, "%d,", &a[i]);
fclose(fp);
}
void writeDat()
{
FILE *fp;
int i;
fp = fopen("OUT12.DAT", "w");
fprintf (fp, "%d\n",cnt);
for(i=0; i
fprintf(fp, "%d,\n", b[i]);
fclose(fp);
}
附件下載:計算機三級網絡技術精選備考試題(3)
相關推薦:
北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內蒙古 |