Reputation: 3250
I have this code:
int num1 = 11*2;
int num2 = 4;
double d = num2 / num1;
Console.WriteLine(d);
Why is the result 0 and not being converted to double, or gives an error for explicit convertion missing?
Upvotes: 2
Views: 3494
Reputation: 64943
Because C# is a strongly-typed language, and operands of same type against an operation usually result on a value of the same type unless there's some implicit operator to do the opposite.
Why is the result 0
Because the result is 0,1818181818181818
and since operands are int
, there's no way to represent the result so it's truncated.
If you want to get a double
result you must explicitly cast these integers into double
:
int num1 = 11*2;
int num2 = 4;
double d = (double)num2 / (double)num1;
Console.WriteLine(d);
Upvotes: 2
Reputation: 14894
Integer division returns an integer result. It is defined like that in C# language specification. Why? So that integers are closed under basic mathematical operators (+, -, *, /). Also, what should the return type be if it's not integer? There are 3 built-in floating point types in C# - float
, double
and decimal
.
You have to be aware that in C# the type of an expression never depends on the type of the variable the result is assigned to. So the compiler will never check that the type of d
is double
, so it can perform a floating point division instead of integer division.
If you need a double
division, cast at least one of the operands to double
double d = (double)num2 / num1;
Upvotes: 3
Reputation: 1513
It's integer division and common across most programming languages. Dividing 2 integers gives you the largest whole number whereas using the modulus operator gives you the remainder 22 % 4 = 2
.
If you want to get the double value from your calculation, you'll need to cast one of the integers to a double first:
double d = (double)num2/num1;
or
double d = num2/(double)num1;
This, on the other hand, will not give you the result you expect because the integer division will occur first and you'll be casting that value to the double:
double d = (double)(num2/num1);
There is a lot of material online about this topic. A few places to look:
https://en.wikipedia.org/wiki/Division_(mathematics)#Of_integers http://mathworld.wolfram.com/IntegerDivision.html
Upvotes: 4
Reputation: 2263
The decimal points are truncated when dividing two ints as it performs an integer division. You have to explicitly cast to double double d = double(num2 )/ num1;
Upvotes: 0
Reputation: 571
this doesn't work like that. when you divide two integers, you get an integer result, and when it tries to implicitly cast it to double, it just fails.
what you'd rather do is
double d = num2 / (double)num1;
cast at least one of them to double, so the compiler understands that it's fractional division you want.
Upvotes: 1