运行此代码时为什么会得到四舍五入的输出?

时间:2019-05-15 18:28:54

标签: java methods division

我试图使这段代码将英寸转换为英尺,但是每当我尝试获取输出时,即使将其作为浮点数返回,我都会将其四舍五入。

我尝试过更改代码以执行模函数+除法函数,但是仅给出了余数。我是代码新手,所以这可能真的很容易,只是似乎无法弄清楚。

``````````````JAVA''`````````````````````` ````` //这是我用来输出的方法。

public static void main(String[] args) {
    System.out.println(calcFeetAndInchesToCentimeters(34));
}

//这是我实际用来计算的方法。

public static float calcFeetAndInchesToCentimeters(int inches){
    if(inches >= 0){
        return inches / 12;
    }else{
        return -1;
    }
 }

输出: 2.0



I would like to have the output be when I run the code above 2.83, however,​ I am only getting the rounded down version. I am not trying to find a 

3 个答案:

答案 0 :(得分:0)

您正在将整数传递给方法并除以int,因此结果将始终为int。要解决此问题,只需将您的方法更改为:

    public static float calcFeetAndInchesToCentimeters(float inches){}

答案 1 :(得分:0)

Typecast英寸浮动,然后分开。

public static float calcFeetAndInchesToCentimeters(int inches) {
    if (inches >= 0) {
        return ((float) inches) / 12;
    } else {
        return -1;
    }
}

答案 2 :(得分:0)

您可以将整数转换为浮点数,然后尝试

plugins {
    id "java-library"
    id "org.springframework.boot" version "2.1.4.RELEASE"  apply false // do not apply it
}
apply plugin: "io.spring.dependency-management"

dependencies {
    // Spring Boot deps 
    implementation "org.springframework.boot:spring-boot-starter-web"

    // libraries you want to "propagate to consumers
    // api group: 'com.google.guava', name: 'guava', version: '23.0'

    // libraries you don"t want to flow in consumers projects
    // implementation ....

    // Test deps
    testImplementation "org.springframework.boot:spring-boot-starter-test"
}
dependencyManagement {
    imports {
        mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES
    }
}