My assignment is as follows:
Read 20 pairs of numbers (ID number and score respectively) into two separate arrays. Find the average score. Print a table as shown below of the ID, score and difference (score - average) for each student, one student per line. Print the sum, average, and count of score at the head of the table as shown. Round the average and difference to 2 decimal places.
I have a bug in my program that should be really simple, but I just can't figure it out for some reason. I've figured out how to do the whole thing, but for some reason, my subtraction is off. Here's a sample output for reference:
ID Score Difference
115 257.0 14.349999999999994
123 253.0 10.349999999999994
116 246.0 3.3499999999999943
113 243.0 0.3499999999999943
112 239.0 -3.6500000000000057
104 239.0 -3.6500000000000057
110 238.0 -4.650000000000006
218 243.0 0.3499999999999943
208 242.0 -0.6500000000000057
222 223.0 -19.650000000000006
223 230.0 -12.650000000000006
213 229.0 -13.650000000000006
207 228.0 -14.650000000000006
203 224.0 -18.650000000000006
305 265.0 22.349999999999994
306 262.0 19.349999999999994
311 256.0 13.349999999999994
325 246.0 3.3499999999999943
321 245.0 2.3499999999999943
323 245.0 2.3499999999999943
The problem is that when I call my program to just print the average that it's computed, it's a nice rounded 242.65. And since the score[k] is obviously also a round number, I don't understand how this is happening? Any way you can shed some light on what's going wrong here?
import java.util.Scanner;
import java.io.*;
public class prog402a
{
public static void main(String args[])
{
Scanner inFile = null;
try
{
inFile = new Scanner(new File("prog402a.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
System.exit(0);
}
int[] idNumber = new int[20];
double[] score = new double[20];
for(int k = 0; k < idNumber.length; k++)
{
idNumber[k] = inFile.nextInt();
score[k] = inFile.nextDouble();
}
double sum = 0;
for(int k = 0; k < score.length; k++)
{
sum += score[k];
}
double doubSum = (double)sum;
double average = doubSum/20.0;
average=(int)(average*100+.5)/100.0;
System.out.println(average);
System.out.println("ID\tScore\tDifference");
for(int k = 0; k < idNumber.length; k++)
{
System.out.println(idNumber[k] + "\t" + score[k] + "\t" + (score[k] - average));
}
inFile.close();
}
}