Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you are observing is the result of <strong>integer truncation</strong>. When doing integer division with two integer operands, the result will be another integer, with the <em>fractional</em> part thrown away. Note that this is different from rounding, e.g, with truncation 3.8 will become 3.</p> <p>This will give you your expected output:</p> <pre><code>double sum = ((117+130) / 3.0) + ((130+13) / 3.0); </code></pre> <p>since we divide by <code>3.0</code> rather than <code>3</code>.</p> <p>I.e., if at least <em>one</em>, or <em>both</em> of the operands in an integer division is a float type, the result will be a float. (Note that I'm using float/double here somewhat interchangeably with regard to <code>int</code>s and truncations)</p> <p>In addition to appending a <code>.</code> or <code>.0</code> to values (<code>.0</code> will generate a <code>double</code>, while <code>.0f</code> will generate a <code>float</code> - as pointed out by @Morwenn's helpful comment below), we can also explicitly cast ints to floats, but it matters <em>when</em> we do it. A simple example (note that the values end up as <code>float</code> <em>after</em> the assignment in this example in any case since <code>v</code> is a <code>float</code>):</p> <pre><code>float v = 0; /* values shown are BEFORE assignment */ v = (5 / 2); /* value is 2 due to integer truncation before assignment */ v = (float) (5 / 2); /* 2.0 as integer division occurs 1st, then cast to float */ v = (float) 5 / 2; /* 2.5 since 5 becomes 5.0 through casting first. */ </code></pre> <p>I borrowed the above example from <a href="https://stackoverflow.com/a/11060283/1209279">Division and floating points</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload