📜  快速求两个数的平均值,无需除法

📅  最后修改于: 2021-05-25 01:24:30             🧑  作者: Mango

给定两个数字,不使用除法即可求出其平均值的下限。

Input : x = 10, y = 12
Output : 11

Input : x = 10, y = 7
Output : 8
We take floor of sum.

这个想法是使用右移运算符,而不是(x + y)/ 2,我们做(x + y)>> 1

C
// C program to find average without using
// division.
#include 
 
int floorAvg(int x, int y) {
     return (x + y) >> 1; }
 
int main() {
  int x = 10, y = 20;
  printf("\n\nAverage = %d\n\n", floorAvg(x, y));
  return 0;
}


Java
// Java program to find average
// without using division
class GFG
{
    static int floorAvg(int x, int y) {
    return (x + y) >> 1; }
     
    // Driver code
    public static void main (String[] args)
    {
        int x = 10, y = 20;
        System.out.print(floorAvg(x, y));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to find average
# without using division.
def floorAvg(x, y):
    return (x + y) >> 1
 
# Driver code
x = 10
y = 20
 
print("Average ", floorAvg(x, y))
 
# This code is contributed by sunny singh


C#
// C# program to find average
// without using division
using System;
 
class GFG
{
    static int floorAvg(int x, int y)
    {
      return (x + y) >> 1;
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int x = 10, y = 20;
        Console.Write("Average = ");
        Console.Write(floorAvg(x, y));
    }
}
 
// This code is contributed by parashar...


PHP
> 1;
     
}
 
    // Driver Code
    $x = 10;
    $y = 20;
    echo "Average = ", floorAvg($x, $y);
 
// This Code is contributed by Ajit
?>


Javascript


输出:
Average = 15

应用范围:
在许多标准算法(例如合并排序,二进制搜索等)中,我们需要两个数字的平均值的下限。由于我们使用按位运算运算符而不是除法,因此上述求平均值的方式更快。