Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just some minor modification to your code will do (with some var renaming for clarity) :</p> <pre><code>double sum = 0; //average will have decimal point for(int i=0; i &lt; args.length; i++){ //parse string to double, note that this might fail if you encounter a non-numeric string //Note that we could also do Integer.valueOf( args[i] ) but this is more flexible sum += Double.valueOf( args[i] ); } double average = sum/args.length; System.out.println(average ); </code></pre> <p>Note that the loop can also be simplified:</p> <pre><code>for(String arg : args){ sum += Double.valueOf( arg ); } </code></pre> <p>Edit: the OP seems to want to use the <code>args</code> array. This seems to be a String array, thus updated the answer accordingly.</p> <p><strong>Update</strong>:</p> <p>As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:</p> <pre><code>BigDecimal sum = BigDecimal.ZERO; for(String arg : args){ sum = sum.add( new BigDecimal( arg ) ); } </code></pre> <p>This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):</p> <ul> <li>Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)</li> <li>The probability of overflow is practically eliminated. Note however, that a <code>BigDecimal</code> might be bigger than what fits into a <code>double</code> or <code>long</code>.</li> </ul>
    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