1

我面临一个奇怪的问题。

if ( c2==c1){
    c3 *= 2 ; 
    System.out.println( c3 ) ; 
    .....
}

我想在 println 语句中插入 c3*2 。但

if ( c2==c1){
    System.out.println( c3*2 ) ; 

给了我不同的结果。

这是整个代码:

        public static void main(String [] args) {

           int c1 = Integer.parseInt(args[0]) ;
           int c2 = Integer.parseInt(args[1]) ;
           int c3 = Integer.parseInt(args[2]) ;

/*  1 */       if ( c1 != c3 ){
/*  2 */        if (c2==c1){
/*  3 */              
/*  4 */              System.out.println(c3 + c2 ) ; 
/*  5 */              c3 *= c2 ; 
/*  6 */        }

/*  7 */       }else{ 
/*  8 */        if ( c2==c1){
/*  9 */                    c3 *= 2 ; 
/* 10 */                    System.out.println( c3 ) ; 
/* 11 */                    c3 *= c2 ; 
/* 12 */            if ( c1 < c2 ) c2 += 7 ;
/* 13 */                   else c2 += 5 ; 
/* 14 */               }}

/* 15 */       System.out.println( c1+c2+c3) ;     
        }          
        .....
    }

有任何想法吗?

4

4 回答 4

7
c3 *= 2; 
System.out.println( c3 ) ; 

将打印与以下内容相同的内容:

System.out.println( c3 * 2 ) ; 

但关键的区别在于,在第一种情况下,c3变量的值将被修改(乘以 2),而在第二种情况下,它将保持不变。

于 2010-10-31T09:11:07.517 回答
3

根据变量的类型,可能会得到不同的结果 - 请记住*=(以及++,--等)将结果转换为与c3. 例如:

byte b = 100;
System.out.println(b*2); // 200
b*=2;
System.out.println(b); // -56

示例:http: //ideone.com/ojKfA

于 2010-10-31T09:15:27.143 回答
1

如果您这样做c3 *= 2;,它将更改其值,c3该值将打印与最后一行不同的值System.out.println( c1+c2+c3);。因此,您需要遵循程序的逻辑。

于 2010-10-31T09:35:09.690 回答
1

如果你想修改变量并同时打印它,你可以这样做:

System.out.println(c3 *= 2);
于 2010-10-31T09:40:13.903 回答