2017-07-24 38 views
-1

任何人能向我解释为什么n1的价值不是由1在这种情况下增加,或者换句话说,为什么数学运算没有显示1增量在Java

package com.company; 

public class Main { 

    public static void main(String[] args) { 

     System.out.println(isNumber(20, 21)); 
    } 
    public static double isNumber (double n1, double n2){ 

     double calc = n1++/n2; 
     return calc; 
    } 
} 
+1

它是后增量运算符,它在返回结果后增加值。 '++ n1'会在计算中返回一个递增的数字。 – Rogue

+1

你已经用[tag:post-increment]标记了这个...你明白“post-increment”中的“post”是什么意思,而不是* pre-increment * ...? – deceze

+3

[C,C++,Java和C#中的前后增量运算符行为]的可能重复(https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-cc-java- c-sharp) –

回答

0

该值增加,但执行后双线calc = n1++/n2;

发生这种情况是因为您使用了后增量操作符。如果你需要的分裂之前应用增量

public class Main { 

    public static void main(String[] args) { 
     System.out.println(isNumber(20, 21)); 
    } 

    public static double isNumber (double n1, double n2){ 
     double calc = n1++/n2; 
     System.out.println(n1); // Prints 21 
     return calc; 
    } 
} 

您的代码就相当于

public static double isNumber (double n1, double n2){ 

     double calc = n1/n2; 
     n1 = n1 + 1; 
     return calc; 
    } 

,你需要应用前增量操作如下:

double calc = ++n1/n2; 

使用前增量该代码相当于:

public static double isNumber (double n1, double n2){ 
    n1 = n1 + 1; 
    double calc = n1/n2; 
    return calc; 
} 
2

结果将稍微小于1

n1++/n2被评价为20.0/21.0副作用的n1被增加1,这意味着将n1然后恰好21.020.01递增浮点double是准确的。这对调用者中的n1的值没有影响,因为在Java中通过值以值传递参数。

你想++n1/n2