0

I was wondering if there is an operator in C++ that does the same thing as // operator in Python (floor division)?

  • 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 Answers2

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
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