两个数字相互交换java_交换两个数字的java程序

例子1:使用临时变量交换两个数字public class SwapNumbers {

public static void main(String[] args) {

float first = 1.20f, second = 2.45f;

System.out.println("--Before swap--");

System.out.println("First number =" + first);

System.out.println("Second number =" + second);

// Value of first is assigned to temporary

float temporary = first;

// Value of second is assigned to first

first = second;

// Value of temporary (which contains the initial value of first) is assigned to second

second = temporary;

System.out.println("--After swap--");

System.out.println("First number =" + first);

System.out.println("Second number =" + second);

}

}

运行程序时,输出为:--Before swap--

First number = 1.2

Second number = 2.45

--After swap--

First number = 2.45

Second number = 1.2

例子2:不使用临时变量交换两个数字public class SwapNumbers {

public static void main(String[] args) {

float first = 12.0f, second = 24.5f;

System.out.println("--Before swap--");

System.out.println("First number =" + first);

System.out.println("Second number =" + second);

first = first - second;

second = first + second;

first = second - first;

System.out.println("--After swap--");

System.out.println("First number =" + first);

System.out.println("Second number =" + second);

}

}

运行程序时,输出为:--Before swap--

First number = 12.0

Second number = 24.5

--After swap--

First number = 24.5

Second number = 12.0

在上面的程序中,我们使用简单的数学来交换数字,而不是使用临时变量。

对于该操作,存储 ( first -second )很重要,first = first - second;

first = 12.0f - 24.5fsecond = first + second;

second = (12.0f - 24.5f) + 24.5f = 12.0ffirst = second - first;

first = 12.0f - (12.0f - 24.5f) = 24.5f

交换的数字使用println()在屏幕上打印。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值