計算用戶輸入的數字的平均數,並輸出所有大於平均數的數

#include<stdio.h>

int main()
{
   int x;
   double sum = 0;
   int cnt = 0;
   int number[100]; //定義數組
   scanf("%d", &x);
   while( x != -1 ){
       number[cnt] = x; //對數組中的元素賦值
       //調試
       {
           int i;
           printf("%d\t", cnt);
           for (i = 0; i<=cnt; i++){
               printf("%d\t",number[i]);
           }
           printf("\n");
       }
       //
       sum += x;
       cnt ++;
       scanf("%d", &x);
   }
   if( cnt > 0){
       printf("%f\n", sum/cnt);
       int i;
       for( i=0; i<cnt; i++){ //使用數組中的元素,遍歷數組
           if(number[i] > sum/cnt ){
               printf("%d\n",number[i]);
           }
       }
   }
   
   return 0;
}

上述程序存在安全隱患: 

cnt可能會超過數組的大小,即cnt>100。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章