+ 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 ?
12 Answers
+ 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.
+ 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??
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.
0
Maybe it should be: Console.WriteLine( {0}, ((double)x%y));
Did not check if it works this way.
0
10 and 2 are of type int, so the result is of type int.
0
Because you should enter one of the number with kind 10.0 or 2.0
0
Any remainder is dropped of to return a integer value
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
- 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)?
- 1
simply,when double is not mentioned (before 2)it gives approximate value....
- 1
because 10/2 =5
- 2
(x)