给定的阵列ARR []其中ARR [i]为汁在第i个玻璃的浓度。当所有玻璃按等比例混合时,任务是求出所得混合物的浓度。
例子:
Input: arr[] = {10, 20, 30}
Output: 20
Input: arr[] = {0, 20, 20}
Output: 13.3333
方法:由于果汁按等比例混合,因此最终浓度将为所有单个浓度的平均值。因此,所需的答案将是sum(arr)/ n ,其中n是数组的大小。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the concentration
// of the resultant mixture
double mixtureConcentration(int n, int p[])
{
double res = 0;
for (int i = 0; i < n; i++)
res += p[i];
res /= n;
return res;
}
// Driver code
int main()
{
int arr[] = { 0, 20, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << mixtureConcentration(n, arr);
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the concentration
// of the resultant mixture
static double mixtureConcentration(int n, int []p)
{
double res = 0;
for (int i = 0; i < n; i++)
res += p[i];
res /= n;
return res;
}
// Driver code
public static void main (String[] args)
{
int []arr = { 0, 20, 20 };
int n = arr.length;
System.out.println(String.format("%.4f",
mixtureConcentration(n, arr)));
}
}
// This code is contributed by chandan_jnu
Python3
# Python3 implementation of the approach
# Function to return the concentration
# of the resultant mixture
def mixtureConcentration(n, p):
res = 0;
for i in range(n):
res += p[i];
res /= n;
return res;
# Driver code
arr = [ 0, 20, 20 ];
n = len(arr);
print(round(mixtureConcentration(n, arr), 4));
# This code is contributed
# by chandan_jnu
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the concentration
// of the resultant mixture
static double mixtureConcentration(int n, int []p)
{
double res = 0;
for (int i = 0; i < n; i++)
res += p[i];
res /= n;
return Math.Round(res,4);
}
// Driver code
static void Main()
{
int []arr = { 0, 20, 20 };
int n = arr.Length;
Console.WriteLine(mixtureConcentration(n, arr));
}
}
// This code is contributed by chandan_jnu
PHP
输出:
13.3333
时间复杂度: O(N)