给定两个数字,在不使用除法的情况下找出它们的平均值。
null
Input : x = 10, y = 12Output : 11Input : x = 10, y = 7Output : 8We take floor of sum.
这个想法是使用 右班操作员 ,而不是做(x+y)/2,我们做(x+y)>>1
C++
// C++ program to find average without using // division. #include <bits/stdc++.h> using namespace std; int floorAvg( int x, int y) { return (x + y) >> 1; } int main() { int x = 10, y = 20; cout << "Average = " << floorAvg(x, y) <<endl; return 0; } // This code is contributed by famously. |
C
// C program to find average without using // division. #include <stdio.h> int floorAvg( int x, int y) { return (x + y) >> 1; } int main() { int x = 10, y = 20; printf ( "Average = %d" , 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
<?php // PHP program to find average // without using division. // function returns // the average function floorAvg( $x , $y ) { return ( $x + $y ) >> 1; } // Driver Code $x = 10; $y = 20; echo "Average = " , floorAvg( $x , $y ); // This Code is contributed by Ajit ?> |
Javascript
<script> // Javascript program to find // average without using // division. function floorAvg(x, y) { return (x + y) >> 1; } // Driver code var x = 10, y = 20; document.write( "Average = " + floorAvg(x, y)); // This code is contributed by noob2000 </script> |
输出:
Average = 15
应用: 在许多标准算法中,我们需要两个数的平均下限,比如 合并排序 , 二进制搜索 等。由于我们使用位运算符而不是除法,上述求平均值的方法更快。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END