0
How to get an integer rather than a decimal
It is said that using a single slash to divide numbers produces a decimal, so what if I just want an integer? For example, 10 / 2 = 5.0 How can I get an outcome of 5? Sorry for my poor English. I hope you guys can understand what I’m saying.
2 odpowiedzi
+ 2
Python has a floor division operator (//), which always*(1) returns a whole number.
5 / 2 = 2.5
5 // 2 = 2
Result of the floor division can be both integer and float depending on the operators.
If even one of the operands are float, Python says the result to be float aswell, but still a whole number.
5.0 // 2 = 2.0
5 // 2.0 = 2.0
5.0 // 2.0 = 2.0
You can always convert floating point numbers to integers with the int function*(2).
int(2.0) = 2
int(2.5) = 2
*(1) Floor division doesn't always return a whole number, in case of ZeroDivisionError nothing is returned.
*(2) int is not strictly a function, it is a class, when you call a class like a function, it calls the class constructor.
+ 2
Depends on the language you use. Somatimes you can do something like this:
int res = (int)10/2; //This works in e. g. Java.