How to do floor division in Python/Java/C++

Floor division

In Mathematics and Computer Science, floor is the smallest possible integer value returned for a double or float value (non-integer values).

For example, 8/3 has a non-integer value of 2.6667; so, applying the floor function would return a value of 2.

Code

There are functions used to apply floor in different languages:

C++

In C++, we have to include the cmath library and the function to call floor():

#include <iostream>
#include <cmath>
using namespace std;
int main() {
double ans;
ans = 8.0 / 3.0 ;
cout<<"The normal value for 8/3 would be: "<< ans<<endl;
// now printing the floor value for 6/5
cout<<"The floor value for 8/3 would be: "<< floor(ans)<<endl;
return 0;
}

Python

In python, we can use // operator:

print('Normal value for 8/3:',8/3)
print('Floor value for 8/3:',8//3)

Java

In Java, we can use Math.floor():

class FloorDivision {
public static void main( String args[] ) {
System.out.println( "Normal value for 8/3: ");
System.out.println( 8.0/3.0 );
System.out.println( "floor value for 8/3: ");
System.out.println(Math.floor(8.0/3.0));
}
}

Free Resources