Java 公共静态双方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19755821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:56:32  来源:igfitidea点击:

Public static double method?

java

提问by Azaria Gebo

import java.util.Scanner;

public class test {

    private static int number1 = 100;
    private static int number2 = 1;

    public static double avgAge() {

        return (number1 + number2) / 2;
    }

    public static void main(String[] args) {

        System.out.println("Average number: " + test.avgAge());
    }   
}

Why does test.avgAge() = 50.0 instead of 50.5? Is there a way to output 50.5 instead?

为什么 test.avgAge() = 50.0 而不是 50.5?有没有办法输出 50.5 呢?

回答by CompuChip

The calculation is done as an integer calculation.

计算是作为整数计算完成的。

If you replace 2 by 2.0 you will get 50.5. I recommend adding a comment to that line to explain this to future readers. Alternatively you can explicitly cast to a double:

如果用 2.0 替换 2,您将得到 50.5。我建议在该行添加一条评论,向未来的读者解释这一点。或者,您可以显式转换为双精度:

((double) (number1 + number2)) / 2

回答by L Q

return ((double)(number1 + number2)) / 2;

回答by shankar

Just replace this function

只需更换此功能

import java.util.Scanner;

public class test {

private static int number1 = 100;
private static int number2 = 1;

public static double avgAge() {

    return (number1 + number2) / 2.0;
}

public static void main(String[] args) {

    System.out.println("Average number: " + test.avgAge()); //Average number: 50.5
}   
}

回答by But I'm Not A Wrapper Class

It's because you're using intsthrough out the calculation before returning it as a double. Do the following:

这是因为您ints在将其作为double. 请执行下列操作:

private static double number1 = 100.0;
private static double number2 = 1.0;

Change these to double. Also, change the 2 to 2.0:

将这些更改为double. 另外,将 2 更改为 2.0:

    return (number1 + number2) / 2.0;

Read more about intsand doubleshere:

了解更多关于intsdoubles在这里:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

回答by coding_idiot

That's because of type promotion.

那是因为类型提升。

If in an operation, any of the operands is a double, then the result is promoted to double.

如果在一个操作中,任何一个操作数是双精度值,则结果被提升为双精度值。

Since here all operands are ints, the division results in an int.

由于这里所有操作数都是整数,因此除法结果为整数。

Type Promotion

类型促销