不使用第三个变量交换两个数字的程序

2025 年 1 月 8 日 | 3 分钟阅读

此程序旨在如下交换/互换两个数字,而不使用第三个数字。

示例: 假设有两个数字 25 和 23。

X= 25 (First number), Y= 23 (second number)
Swapping Logic:
X = X + Y = 25 +23 = 48
Y = X - Y = 48 - 23 = 25
X = X -Y = 48 - 25 = 23
and the numbers are swapped as X =23 and Y =25. 

算法

  • 步骤 1: 开始
  • 步骤 2: 输入 x, y
  • 步骤 3: 打印 x, y
  • 步骤 4: x = x + y
  • 步骤 5: y= x - y
  • 步骤 6: x =x - y
  • 步骤 7: 打印 x, y
  • 步骤8: 结束

Java 程序

输出

Enter the value of x and y
23  43
before swapping numbers: 23  43
After swapping:  43  23

C 语言程序

输出

Enter the value of x and y?
13 
22
before swapping numbers:  13  22
After swapping:  22  13

C# 程序

输出

Enter the value of x and y
213 
432
before swapping numbers: 213   432
After swapping:  432   213

Python 程序

输出

Enter the value of x? 
12
Enter the value of y? 
24
before swapping numbers:  12   24
After swapping:  24   12

PHP 程序

输出

Enter the value of x   55
Enter the value of y   46
before swapping numbers:  55  46
After swapping  46  55
下一主题#