I am trying to solve this exercise Problem 22 just for reinforcing my solving skills. I've already coded the answer. The task asks for "what is the sum of ALL the resulting y coordinates values? (Enter the number as a decimal in the form xxxxx.x (I dont understand what this means)) . My answers is 50616.0, but it is wrong. I hope you can help me. I don't know if I am doing wrong, or just I don't understand what the task means in the form xxxxx.x, I think it is decimal, no?
This is my code:
import java.io.*;
import java.math.BigDecimal;
public class Problema22 {
public static void main(String args[]) {
File archivo = null;
FileReader fr = null;
BufferedReader br = null;
try {
archivo = new File("C:\\plane22.txt");
fr = new FileReader(archivo);
br = new BufferedReader(fr);
String linea;
int index = 0;
int num = 0;
String num2 = "";
BigDecimal sol = BigDecimal.valueOf(0);
while ((linea = br.readLine()) != null) //System.out.println(linea);
{
//System.out.println(linea);
int line1 = linea.indexOf(",");
int line2 = linea.lastIndexOf(",");
int line3 = linea.indexOf("|");
String y1 = linea.substring(line1+1, line3);
String y2 = linea.substr开发者_开发技巧ing(line2+1, linea.length() );
long sumys = (Integer.parseInt(y1)+ Integer.parseInt(y2))/2;
sol = BigDecimal.valueOf(sumys).add(sol);
//System.out.println(sol);
}
System.out.println(sol);
//count((ArrayList<String>) arr);
} catch (Exception e) {
e.printStackTrace();
}
}
They want the result in the form "xxxxx.x", meaning 5 digits before the dot and one after. Your answer is incorrect because it is an integer, while they want a floating point number.
I think your error is introduced in this line:
long sumys = (Integer.parseInt(y1)+ Integer.parseInt(y2))/2;
The /2
will truncate the .5
if the sum of the two Y coordinates is odd. As it is for this line:
170,509|341,54
You compute 281
for this one, but the midpoint's Y coordinate is 281.5
.
I suggest parsing all the numbers into floating point variables and storing the intermediate results into floating point variables. A standard double
should have the mantissa to accurately handle this data set.
精彩评论