java - 对数字(float)进行舍入以将其存储为 int,而不使用像 math.round() 这样的 math.packe

标签 java floating-point int rounding

从摄氏温度计算华氏温度的简单程序,但是如果不使用 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/

相关文章:

java - 将自定义标识符分配给 @id 属性

go - 生成可以返回所有可能值的均匀随机 float

c# - 在 C# 中,为什么在声明 int 时不使用 'new' 关键字?

c# - 当可能为空字符串值时,将字符串数组值转换为 int

C# float.ToString 舍入值

java - 为什么我的代码给出了这个数学问题的错误答案?

java - 作为枚举成员的数组编译失败

java - 无法解析模板 "Class"

java - 如何在java中搜索字符串及其后面的数字

junit - JUnit或Hamcrest是否具有公差声明?