使用 C++ 查詢調和均值,使用算術平均數和幾何平均數。


本文我們將演示如何利用算術平均數和幾何平均數來獲取調和平均數。這三個平均值的計算公式如下 −

  • 算術平均數 − (a + b)/2
  • 幾何平均數 − $$\sqrt{\lgroup a*b\rgroup}$$
  • 調和平均數 − 2ab/(a+b)

調和平均數可以使用算術平均數和幾何平均數表示,利用以下公式 −

$$HM=\frac{GM^{2}}{AM}$$

示例

即時演示

#include <iostream>
#include <cmath>
using namespace std;
double getHarmonicMean(int a, int b) {
   double AM, GM, HM;
   AM = (a + b) / 2;
   GM = sqrt(a * b);
   HM = (GM * GM) / AM;
   return HM;
}
int main() {
   int a = 5, b = 15;
   double res = getHarmonicMean(a, b);
   cout << "Harmonic Mean of " << a << " and " << b << " is " << res ;
}

輸出

Harmonic Mean of 5 and 15 is 7.5

更新於:2019 年 10 月 30 日

289 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.