double energy, mass;
double speedOfLight = 299792458.0;
// Get mass
System.out.print("Mass? ");
mass = keyboard.nextDouble();
// Calculate energy
energy = mass*Math.pow(speedOfLight, 2);
// Round to 1 decimal place
energy = Math.round(energy * 10.0) / 10.0;
System.out.printf("The energy is " +energy+ " Joules");
// Close scanner
keyboard.close();它正在返回,“能量是8.987551787368176E16焦耳”,而它应该返回,“能量是89875517873681760.0焦耳”
发布于 2018-08-24 05:05:19
Math.round按预期工作,返回最接近的整数(但输出为scientific notation格式)。问题出在号码的打印上。您可以使用printf的format specifiers以您想要的格式打印数字:
System.out.printf("The energy is %.1f Joules", energy);https://stackoverflow.com/questions/51994216
复制相似问题