Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the <code>=</code> to match the data on the other side according to a set of predefined rules.</p> <p>When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).</p> <p>In this case you have <code>double var = integer result</code> which casts the integer result to a double <em>after the calculation</em> in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).</p> <p>If you'd like to keep the result as a double you're going to want to create a situation where you have <code>double var = double result</code></p> <p>The easiest way to do that is to force the expression on the right side of an equation to cast to double:</p> <p><code>c = a/(double)b</code></p> <p>Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).</p> <p>After the upcast, <code>a</code> will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.</p> <p><strong>AGAIN,</strong> please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.</p>
 

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