Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?
A:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum = i / (i + 1);
}
System.out.println("Sum is " + sum);
B:
double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1);
}
System.out.println("Sum is " + sum);
C:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += 1.0 * i / (i + 1);
}
System.out.println("Sum is " + sum);
D:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += i / (i + 1.0);
}
System.out.println("Sum is " + sum);
E:
double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1.0);
}
System.out.println("Sum is " + sum);
a. BCD
b. ABCD
c. B
d. CDE
e. CD
e Note that 1 / 2 is 0.5 in a math expression. In Java, however, integer division yields an integer. The fraction part is truncated. Therefore, i / (i + 1) is 0 . (A) and (B) are incorrect. (E) is incorrect because the last i in the loop is 98 . So the last item 99 / 100.0 is not added to sum. So, the correct answer is CD.
You might also like to view...
For a long text label use the "________" key and "Enter" key combination to insert a line break so the text appears on two lines within the cell
Fill in the blank(s) with correct word
To add a row to the bottom of a table, place the insertion point in the last cell and tap the __________ key.
Fill in the blank(s) with the appropriate word(s).
=MATCH(value,array,0) =VLOOKUP(value, table, column index, 0) The 0 (zero) in these two functions above work EXACTLY the same.
a. true b. false
What is an answer file, and how is it created?
What will be an ideal response?