-5

I understand that a double is a decimal. In the following program the output is 1 even though I thought it would be 1.05 repeating.

static void Main (string[] args)
{
double d = 19 / 18;
Console.WriteLine(d);
Console.ReadKey();
}

Am I misunderstanding double?

vroomvsr
  • 93
  • 2
  • 8
  • You are misunderstanding integer math: `Integer-19` divided by `Integer-18` results in a Integer: `1`. Try `19.0 / 18.0` – abelenky Mar 26 '15 at 20:11
  • "I understand that a double is a decimal" - not really. It's a binary floating point number, although that's not the problem you've got. Your actual problem is you're performing integer division, then converting the result (an integer) into a double... – Jon Skeet Mar 26 '15 at 20:12
  • [C# Reference Division Operator](https://msdn.microsoft.com/en-us/library/aa691373(v=vs.71).aspx) – Steve Mar 26 '15 at 20:12
  • 3
    Come on, millions of times asked and answered.... – EZI Mar 26 '15 at 20:14
  • `double d = 19 / 18;` -> `double d = (double)(19 / 18);` -> `double d = (double)(1);` -> `double d = 1.0d;` – Zéychin Mar 26 '15 at 20:20

1 Answers1

3

You are misunderstanding integer math.

Integer-19 / Integer-18 results in an Integer with value 1.

(that you assign the value to a double is not relevant. The calculation results in an Integer).

To fix it, use:

double d = 19.0 / 18.0;
abelenky
  • 63,815
  • 23
  • 109
  • 159