Thursday, September 29, 2011

Challenge 014’s Solution

In Challenge 14, the output displays “0.0”. This is because the expression “double n = 99/100” is written with int values for the numbers 99 and 100. Because of this, the result of 99 ÷ 100 must also be an int value, and therefore equals 0. The number 0 is converted to a double value after the function is performed, which is why the statement “0.0” is displayed. To combat this problem, one can do either of two solutions: first, one can simply write the numbers 99 and 100 as double values, replacing the previous expression with “double n = 99.0/100.0”. Because of their new notation, the resulting output will be “0.99”. Second, one can convert each number into a double value within the equation itself, replacing the previous expression with “double n = (double)99/(double)100”. This makes 99 and 100 into the quantities 99.0 and 100.0, respectively, resulting (again) in the output “0.99”.
 
−Phoenix

3 comments:

  1. HI Phoenix, try this and let me know what happens (and of course, why it happened):

    double n = 99 / (double) 100;

    Thank you.

    ReplyDelete
  2. With the code “double n = 99 / (double) 100;”, the output is “0.99”. This is because the number 100 is converted to the “double” value 100.0. Then, when the “int” value 99 is divided over the “double” value 100.0, the result is the “double” value 0.99. Therefore, when one of the quantities in an equation is a “double” value, the result is a “double” value, (unless converted to an “int” value later on).

    −Phoenix

    ReplyDelete
  3. Very good. 15 XPs are awarded for this completion.

    ReplyDelete