Question: Why is my code not presenting the correct average for the numbers given : 5.25 6.75 8.85 9.0 Q The code is: import java.util.Scanner; public
Why is my code not presenting the correct average for the numbers given :
5.25 6.75 8.85 9.0 Q
The code is:
import java.util.Scanner;
public class lab6b {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Initialize variables double sum = 0; double smallest = Double.POSITIVE_INFINITY; double largest = Double.NEGATIVE_INFINITY;
while (scanner.hasNextDouble()) { double number = scanner.nextDouble(); sum += number; if (number < smallest) { smallest = number; } if (number > largest) { largest = number; } }
// Compute and output results int count = (int) (sum == 0 ? 1 : Math.ceil(Math.log10(Math.abs(sum))) + 1); System.out.println("Data Set Value"); System.out.printf("%-" + count + "s %-15s%n", "The average of the values is:", sum == 0 ? "N/A" : String.format("%.2f", sum / count)); System.out.printf("%-" + count + "s %-15.2f%n", "The smallest value is: ", smallest); System.out.printf("%-" + count + "s %-15.2f%n", "The largest value is: ", largest); System.out.printf("%-" + count + "s %-15.2f%n", "THe range is: ", largest - smallest); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
