变量互换方法以及自增运算符使用注意事项

本文介绍三种实现变量交换的方法,包括使用临时变量、算术操作和位操作,并探讨自增运算符++的正确使用方式,避免常见错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三种方法实现变量交换:

public class test3{//三种方法实现变量交换
	public static void main(String[] args){
		int a = 1 , b = 2 , c = 3 , d = 4 , e = 5 , f = 6;
		//以下用不同方法实现变量交换;
		//method one
		int temp;
		temp = a;
		a = b;
		b = temp;
		System.out.println(a+"----"+b);
		//method two
		c = c + d;
		d = c - d;
		c = c - d;
		System.out.println(c+"----"+d);
		//method three
		e = e ^ f;
		f = e ^ f;
		e = e ^ f;
		System.out.println(e+"----"+f);
	}
}

自增“++”运算符,使用时时应避免的书写方法:

public class test2{//**此代码说明应尽量避免i=i++的写法,如果想用直接i++即可**
	public static void main(String[] args){
		int i = 10;
		i = i++;//**是将i++表达式的值10赋值给i,在执行过程中经历过i=11,但最后此处i被覆盖为10**
		System.out.println(i);
		i = ++i;
		System.out.println(i);
	}

}

输出结果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值