Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>(You said that your variables are ints, <em>a</em> and <em>b</em> is what I've used below, and I'm using this assumption: <code>int a, b;</code>.)</p> <p>The problem with taking the average of two numbers by adding and then dividing is you might overflow (as Laurence Gonsalves alluded to in his comment). If you know that the sum won't exceed <code>INT_MAX</code>, then using <code>int</code> is fine, and nothing more needs to be done:</p> <pre><code>int avg = (a + b) / 2; </code></pre> <p>If the sum might overflow, then moving up to a type which won't overflow, such as <code>long</code>, is fine; however, remember that <code>long</code> and <code>int</code> might be the same size (<code>INT_MAX</code> might equal <code>LONG_MAX</code>), in which case this doesn't help, except that <code>INT_MAX</code> would be much larger&mdash;at least 2,147,483,674.</p> <pre><code>int avg = ((long)a + b) / 2; </code></pre> <p>Note that when <em>b</em> is added to <em>a</em>, <em>b</em> is automatically converted to a <code>long</code>. You might need to cast the final result to <code>int</code> to avoid warnings (including from a lint program):</p> <pre><code>int avg = (int)(((long)a + b) / 2); </code></pre> <p>However, remember that integer limits are defined by the implementation; the real concern is whether the addition could ever be more than <code>INT_MAX</code> and casts are just a way to explicitly specify type and thus avoid that unintentional overflow.</p> <hr> <p>When you want to divide by two, use <code>/ 2</code>, don't try to get clever with bitshifts. Compilers have been smart enough to optimize this kind of thing for years, especially when you use constants, and code clarity is more important.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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. 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