从摄氏温度计算华氏温度的简单程序,但是如果不使用 math.round() 这是否可能?
public class CelsiusZuFahreheit {
public static void main (String [] args){
System.out.println("Temperature-Calculation");
System.out.println("=======================");
System.out.println("C F");
System.out.println("---------");
for(int celsius = 0; celsius<=100; celsius+=3){
float fahrenheit = (float)celsius * 9/5 + 32;
int rFahrenheit = Math.round(fahrenheit);
System.out.printf("%3d %5d\n", celsius, rFahrenheit);
}
}
}
最佳答案
怎么样:
System.out.printf("%3d %5.0f\n", 摄氏度, 华氏度);
由于您纯粹出于演示目的而对值进行舍入,因此将此逻辑移至字符串格式是有意义的。
此外,一般将值保留为 double 可能是一个好主意,因为 83.23 仍然是一个有效的温度值(如果您的要求发生变化并且您需要打印 2 个小数位,则仅更改 1 个字符)。
关于java - 对数字(float)进行舍入以将其存储为 int,而不使用像 math.round() 这样的 math.packe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012295/