📜  程序平均数组而不会发生溢出

📅  最后修改于: 2021-04-17 16:31:38             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是查找数组元素的平均值而不会发生溢出。

例子:

方法:可以根据以下观察结果解决给定问题:

  • N个数组元素的平均值可以通过将数组元素的总和除以N来获得但是,如果数组包含大整数,则计算数组arr []的总和可能会导致整数溢出。
  • 因此,可以通过以下步骤有效地计算数组的平均值:
    • 使用索引范围为[0,N – 1]的变量i遍历数组
    • 更新平均=(平均+(arr [i] –平均)/(i + 1))

请按照以下步骤解决问题:

  • 初始化两个变量,例如sum0avg0 ,分别存储数组元素的和和平均值。
  • 遍历数组arr [],更新avg = avg +(arr [i] – avg)/(i +1),并更新sum = sum + arr [i]。
  • 完成上述步骤后,通过标准方法(即sum / N)打印平均值,并通过有效方法(即avg)打印平均值

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate average of
// an array using standard method
double average(int arr[], int N)
{
    // Stores the sum of array
    int sum = 0;
 
    // Find the sum of the array
    for (int i = 0; i < N; i++)
        sum += arr[i];
 
    // Return the average
    return (double)sum / N;
}
 
// Function to calculate average of
// an array using efficient method
double mean(int arr[], int N)
{
    // Store the average of the array
    double avg = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Update avg
        avg += (arr[i] - avg) / (i + 1);
    }
 
    // Return avg
    return avg;
}
 
// Driver Code
int main()
{
    // Input
    int arr[] = { INT_MAX, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << "Average by Standard method: " << fixed
         << setprecision(10) << average(arr, N) << endl;
 
    cout << "Average by Efficient method: " << fixed
         << setprecision(10) << mean(arr, N) << endl;
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
  
// Function to calculate average of
// an array using standard method
static Double average(int arr[], int N)
{
   
    // Stores the sum of array
    int sum = 0;
 
    // Find the sum of the array
    for (int i = 0; i < N; i++)
        sum += arr[i];
 
    // Return the average
    return Double.valueOf(sum / N);
}
 
// Function to calculate average of
// an array using efficient method
static Double mean(int arr[], int N)
{
   
    // Store the average of the array
    Double avg = 0.0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
 
        // Update avg
        avg += Double.valueOf((arr[i] - avg) / (i + 1));
    }
 
    // Return avg
    return avg;
}
 
// Driver Code
public static void main(String args[])
{
   
    // Input
    int arr[] = {Integer.MAX_VALUE, 1, 2 };
    int N = arr.length;
   
    // Function call
    System.out.println("Average by Standard method: "+ String.format("%.10f", average(arr, N)));
    System.out.println("Average by Efficient method: "+ String.format("%.10f", mean(arr, N)));
}
}
 
// This code is contributed by ipg2016107.


Python3
# Python3 program for the above approach
import sys
 
# Function to calculate average of
# an array using standard method
def average(arr, N):
     
    # Stores the sum of array
    sum = 0
 
    # Find the sum of the array
    for i in range(N):
        sum += arr[i]
 
    # Return the average
    return sum // N * 1.0 - 1
 
# Function to calculate average of
# an array using efficient method
def mean(arr, N):
     
    # Store the average of the array
    avg = 0
 
    # Traverse the array arr[]
    for i in range(N):
         
        # Update avg
        avg += (arr[i] - avg) / (i + 1)
 
    # Return avg
    return round(avg, 7)
 
# Driver Code
if __name__ == '__main__':
     
    # Input
    arr = [2147483647, 1, 2]
    N = len(arr)
 
    # Function call
    print("Average by Standard method: ","{:.10f}".format(
        -1.0 * average(arr, N)))
 
    print("Average by Efficient method: ","{:.10f}".format(
        mean(arr, N)))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to calculate average of
// an array using standard method
static double average(int[] arr, int N)
{
     
    // Stores the sum of array
    int sum = 0;
 
    // Find the sum of the array
    for(int i = 0; i < N; i++)
        sum += arr[i];
 
    // Return the average
    return (double)(sum / N);
}
 
// Function to calculate average of
// an array using efficient method
static double mean(int[] arr, int N)
{
 
    // Store the average of the array
    double avg = 0.0;
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Update avg
        avg += ((double)((arr[i] - avg) / (i + 1)));
    }
 
    // Return avg
    return avg;
}
 
// Driver Code
static public void Main()
{
 
    // Input
    int[] arr = { Int32.MaxValue, 1, 2 };
    int N = arr.Length;
 
    // Function call
    Console.WriteLine("Average by Standard method: " +
         (average(arr, N)).ToString("F10"));
    Console.WriteLine("Average by Efficient method: " +
         (mean(arr, N)).ToString("F10"));
}
}
 
// This code is contributed by Dharanendra L V.


输出:
Average by Standard method: -715827882.0000000000
Average by Efficient method: 715827883.3333332539

时间复杂度: O(N)
辅助空间: O(1)