跳转到内容

C++ 编程/作用域/示例/程序平均值

来自维基教科书,一个开放世界的开放书籍
// Program Average
#include <iostream>

using namespace std;

float a[10];                      /* a is now in scope.*/
int length;                       /* length is now in scope.*/

float average(){
  float result = 0.0;             /* result is now in scope.*/

  for(int i = 0; i < length; i++){ /* i is now in scope.*/
    result += a[i];
  }                               /* i is now out of scope.*/

  return result/length;
}                                 /* result is now out of scope.*/

int main(){
  length = 0;
  cout << "enter a number for each of the next 10 lines" << endl;

  while( length != 10 )
    { cin >> a[length++]; }

  float av = average();            /* av is now in scope.*/
  cout << endl << "average: " << av << endl;

  return 0;
}                                 /* All variables now out of scope.*/
华夏公益教科书