找到你要的答案

Q:Java multiply long and float number, which datatype is the result?

Q:java乘长浮点数,它的数据类型的结果?


can someone explain why 'c' has to be a double although "0.2f" is defining it as float?
I thought the 'f' stands for a float number.
Sorry if this is a stupid question but I am wondering..

    a = 4294967296L;
    b = 'n';
    c = (3.1415926 * 0.2f) * a;

=>

    long a = 4294967296L;
    char b = 'n';
    float c = (3.1415926 * 0.2f) * a;

change 'c' to double =>

    long a = 4294967296L;
    char b = 'n';
    double c = (3.1415926 * 0.2f) * a;


can someone explain why 'c' has to be a double although "0.2f" is defining it as float?
I thought the 'f' stands for a float number.
Sorry if this is a stupid question but I am wondering..

    a = 4294967296L;
    b = 'n';
    c = (3.1415926 * 0.2f) * a;

= & gt;

    long a = 4294967296L;
    char b = 'n';
    float c = (3.1415926 * 0.2f) * a;

change 'c' to double = & gt;

    long a = 4294967296L;
    char b = 'n';
    double c = (3.1415926 * 0.2f) * a;
answer1: 回答1:

That's because 3.1415926 is a double constant. So the expression (3.1415926 * 0.2f) gives a double result which when multiplied by a long is still double.

Btw. if you wanted to multiply by pi, better use Math.PI.

这是因为3.1415926是一个双常数。这样的表达(3.1415926×0.2f)给出了一个双重的结果,当乘以长还是双。

顺便说一下,如果你想乘圆周率,更好的使用math.pi。

answer2: 回答2:

This is because the default type for floating point number is double by the compiler (so the 3.14 consider as double):

// cant compile  3.14 is double and double*something = double
float c = (3.1415926 * 0.2f) * 4294967296L;

// this is ok ( 3.14 is now float and not double.
float c = (3.1415926f * 0.2f) * 4294967296L;

这是因为浮点数的默认类型是编译器的两倍(所以3.14被认为是double):

// cant compile  3.14 is double and double*something = double
float c = (3.1415926 * 0.2f) * 4294967296L;

// this is ok ( 3.14 is now float and not double.
float c = (3.1415926f * 0.2f) * 4294967296L;
answer3: 回答3:

In your example you are using three kind of types: a double, a float and a long. So because of it you have to declare c as a double since double is bigger than float but if you just use

long a = 4294967296L;
char b = 'n';
float c =  0.2f * a;

then c can only be float and not long because declaring c as long will make lose precision to the result and you're program won't compile

在你的例子中,你使用三种类型:一个双,一个浮动和一个长。因此,你必须声明C为双,因为双大于浮动,但如果你只是使用

long a = 4294967296L;
char b = 'n';
float c =  0.2f * a;

然后C只能是浮动而不是长的,因为声明C会使结果丢失精度,并且你的程序不会编译

java  declaration