+ 8

why double x =10/4 gives 2 ?

int x =10/4 gives 2 OK. But why double x =10/4 gives 2 ? why should I run double x =10/4.0 to get 2.5 ?

11th Aug 2016, 1:22 AM
acandas
acandas - avatar
12 ответов
+ 7
C# will evaluate first the operation after the equal sign, where we have 10/4. 10 it's an integer and 4 it's an integer and the result will be an integer 10/4 = 2. After this it will cast the result(an integer) to a double (because x it's a double) and we will have 2.0, and in the output 2.0 will be 2. If we have one member or bouth from the right a double (10.0/4, 10/4.0 or 10.0/4.0) then the result of the operation from the right of the equal sign will be considered a double not an integer, because in this cases where we have double(10.0)/integer(4) the int will be automatically cast to double by the program.
11th Aug 2016, 4:43 AM
Gighi
Gighi - avatar
+ 1
I guess, I need to think that first operation is 10/4. Result is 2. After, second operation is double and it double 2 gives 2. I think it should give 2.0??
22nd Mar 2017, 6:28 PM
acandas
acandas - avatar
0
You should write: double x = (double)10/4; It will tell the compiler that 10 is a double and thus it will evaluate the result as a double.
14th Nov 2016, 9:27 AM
Alexandru Dan Ion
Alexandru Dan Ion - avatar
0
Maybe it should be: Console.WriteLine( {0}, ((double)x%y)); Did not check if it works this way.
22nd Mar 2017, 6:35 PM
Alexandru Dan Ion
Alexandru Dan Ion - avatar
0
10 and 2 are of type int, so the result is of type int.
14th Apr 2017, 1:25 PM
Amazing Kawaii Pikachu
0
Because you should enter one of the number with kind 10.0 or 2.0
21st Apr 2017, 3:18 PM
mohammad reza
mohammad reza - avatar
0
Any remainder is dropped of to return a integer value
26th Apr 2017, 10:32 AM
mei
mei - avatar
0
as @Gighi said "C# will evaluate first the operation after the equal sign" hence the result will be 2. you can try as following to make sure result is 2.5 i.g: double y , x; y = 10; x = 4; Console.Write(y/x); Outputs: 2.5
5th Aug 2021, 1:05 PM
Wais
- 1
is there an option where you can modify the int to a double directly in the writeline parenthesis without modifying the rest of the code? console.writeline(double{0};x%y)?
17th Aug 2016, 1:19 PM
Rares Chitari
Rares Chitari - avatar
- 1
simply,when double is not mentioned (before 2)it gives approximate value....
17th Mar 2017, 12:39 PM
sai venkat
sai venkat - avatar
- 1
because 10/2 =5
1st Apr 2017, 8:50 AM
HACKER HITMAN
HACKER HITMAN - avatar
- 2
(x)
1st Nov 2016, 9:34 AM
Fāšhīøň Bøý Māxtø
Fāšhīøň Bøý Māxtø - avatar