E
E
Evgeny Semashko2020-10-07 22:53:25
C++ / C#
Evgeny Semashko, 2020-10-07 22:53:25

Why was var cast to int?

var x = 7 / 2; // = 3 (int)
Why did it happen? Indeed, in theory, when dividing, we got 3.5 and varshould have become double, but in the end we get intor is it due to the fact that it is not written down and by the first digits it decided to become int? var x = 7.0/2.0

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2020-10-07
@evgenysemashko

7 is int
2 is int
int / int = int
That's it.
If you want double, then you need to write 7.00 / 2.00

C
cicatrix, 2020-10-08
@cicatrix

Evgeny Semashko , These are not subtleties and jokes, but part of the language specification.
(Here's the link if you're interested).
In a nutshell, there are several overloads for each operator, depending on the type of operands. In particular, division (read more here ) provides for integer division, floating point division (IEEE 754), and decimal division.
Here, since both operands are of the same type, integer division is applied. To use another overload, at least one of the operands must be a float or decimal.
7 / 2 = 3
7f / 2 = 3.5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question