21xrx.com
2024-09-20 01:03:05 Friday
登录
文章检索 我的文章 写文章
C++代码:求几何平均值
2023-07-01 06:07:25 深夜i     --     --
C++ geometry mean coding algorithm

几何平均值是指多个数值的乘积的n次方根,其中n为数值的个数。在数学中,几何平均值是一种计算多个数之间平均值的方法。在C++中,我们可以使用以下代码来求几何平均值:


#include <iostream>

#include <cmath>

using namespace std;

int main() {

  int n;

  double product = 1, geometric_mean;

  cout << "Enter the number of values: ";

  cin >> n;

  double values[n];

  // Ask user to input all values

  for (int i = 0; i < n; i++) {

    cout << "Enter value " << i+1 << ": ";

    cin >> values[i];

  }

  // Calculate the product of values

  for (int i = 0; i < n; i++) {

    product *= values[i];

  }

  // Calculate the geometric mean

  geometric_mean = pow(product, 1.0/n);

  cout << "The geometric mean is: " << geometric_mean << endl;

  return 0;

}

在以上代码中,我们首先要求用户输入需要计算几何平均值的数值的个数n。然后,我们定义了一个数组values来存储用户输入的值。接着,我们使用一个for循环来遍历数组,让用户输入n个数值。随后,我们又使用了一个for循环来计算n个数值的乘积,存储到变量product中。最后,我们使用了pow函数来计算乘积的n次方根,得到几何平均值geometric_mean,并输出到屏幕上。

总之,使用以上的C++代码来求几何平均值是非常简单的,只需要输入需要计算平均值的数的个数,输入这些数值,然后运行程序即可得到几何平均数。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复