I was wondering if there is an operator in C++ that does the same thing as // operator in Python (floor division)?
Asked
Active
Viewed 276 times
0
-
3`/` does the thing given you typecast the result into `int`. – DeGo May 03 '21 at 15:11
-
thanks. So typecast to int is like a floor function? – May 03 '21 at 15:14
-
@Cplusplusbeginner: Yes, as long as you remember that all floating points are quasi-unpredictable, so it may floor to a number other than the one you expected – Mooing Duck May 03 '21 at 15:15
-
While `floor` will convert the floating point to 0, `int` typecasting will drop off the floating points altogether. – DeGo May 03 '21 at 15:16
-
You could make a `x = y /floor/ z;` using [infix](https://stackoverflow.com/q/36356668/4641116) technique. Not recommended, though. I suggest `x = std::floor(y / z);` as more idiomatic C++. – Eljay May 03 '21 at 15:16
-
Casting to `int` is a bad suggestion. It shall result in value truncation if the result can't be represented within `int`. – Zoso May 03 '21 at 15:29
2 Answers
1
IN PYTHON
You can use int(a/b)
to get the same result as a//b
.
Basically //
refers to the floor decision and it is exactly the same if we convert a floating-point to an integer by typecasting.
You can even import math and find the floor of a floating-point number.
import math
math.floor(a/b)
FOR C++
Simply divide the variable with the declaration of result as int datatype.
int result = a/b;
or you can use a floor operator
#include <math.h>
using namespace std;
void main(){
std::floor(a/b);
}

Go For Pro
- 115
- 1
- 8
-
-
1For `int result = a/b` , What if `a/b` can't be accommodated in an `int`? – Zoso May 03 '21 at 15:33
-
if the value is too large then we can use `long long int` datatype. – Go For Pro May 03 '21 at 15:36
-
1This is an awful answer, and it's a shame it is upvoted, at least when it comes to C++ part. – SergeyA May 03 '21 at 15:37
0
If lhs
and rhs
are two integers (short
, int
, unsigned long
, ...), lhs / rhs
is the result of the integer division of those two values. Its type follows standard integer promotion.
If either lhs
or rhs
is a floating point, you'd need std::floor(lhs / rhs)
. Alternatives are std::ceil
and std::round
.

YSC
- 38,212
- 9
- 96
- 149