java - Rounding error gives me invalid answer -
i'm having problem rounding. reason can't round testp
tenth place. example, on first given example (alex smith) gives me answer of 82.0, should 82.6.
here assignment has examples: http://www.hpcodewars.org/past/cw5/problems/average.htm
import java.io.file; import java.io.fileoutputstream; import java.io.printwriter; import java.math.*; import java.util.scanner; public class average { public static void main(string[] args) { int num = 0, temp =0;; string filename="averageinput.txt"; string filename2="averageoutput.txt"; scanner inputstream = null; printwriter outputstream = null; double homeworkp = 0; //read try{ inputstream = new scanner(new file(filename)); //try open file } catch(exception e){ system.out.println("could not open file named "+ filename); // if doesn't find it, tell them system.exit(0); // , exit. } //write try{ outputstream = new printwriter(new fileoutputstream(filename2,true)); //try create file } catch(exception e){ system.out.println("could not open file named "+ filename2); // if doesn't find it, tell them system.exit(0); // , exit. } int numh = inputstream.nextint(); int numt = inputstream.nextint(); int[] arrayh = new int[numh]; outputstream.println("averages"); string blank = inputstream.nextline(); while (inputstream.hasnextline()){ string line = inputstream.nextline().replaceall(" h","").replaceall(" t",""); string[] nameparts = line.split(" "); string name = nameparts[0] +" "+ nameparts[1]; (int =0, p=2; < numh; i++, p++){ //collects homework grades. arrayh[i] = integer.valueof(nameparts[p]); temp = temp + arrayh[i]; } homeworkp = (temp - arraymin(arrayh))/(numh-1) ; //gets percentage rounded decimal. //system.out.println("homep: " + homeworkp); temp =0; num = 0; (int p = numh; p < numt + numh; p++){ //collects test grades. num = num + integer.valueof(nameparts[p]); } double testp =num/numt; //gets percentage decimal. system.out.println("homep: "+ homeworkp + "testp: "+ testp); double totalp = (homeworkp * 40) + (testp * 60); system.out.println(name + " " + totalp); } outputstream.close(); inputstream.close(); } public static int arraymin(int[] arr) { int = 0; int min = integer.max_value; if (arr == null) { return 0; } else { while (i < arr.length) { if (arr[i] < min) { min = arr[i]; } i++; } } return min; } }
change
double testp =num/numt;
to
double testp = ((double) num) / numt;
as num
, numt
int
, have integer division, 0
instead of 0.xyz
...
Comments
Post a Comment