C程序交换两个数字
2021-07-06 22:10:13
深夜i
--
--
C
程
序
交
换
两
个
数
字
C 程序使用和不使用第三个变量交换两个数字,使用指针、函数(按引用调用)和使用按位异或运算符。 交换意味着交换。 如果程序有两个变量 a 和 b,其中 a = 4 和 b = 5,将它们交换后,a = 5,b = 4。在第一个 C 程序中,我们使用一个临时变量来交换两个数字。
C语言中两个数的交换
#include <stdio.h>
int main()
{
int x, y, t;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
t = x;
x = y;
y = t;
printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
return 0;
}
下载交换号码程序。
程序的输出:输入两个整数 2345 Before Swapping First integer = 23Second integer = 45After SwappingFirst integer = 45Second integer = 23
交换没有第三个变量的两个数字
您还可以在不使用第三个变量的情况下交换两个数字。 在这种情况下,C 程序将如下所示:
#include <stdio.h>
int main()
{
int a, b;
printf("Input two integers (a & b) to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %d\nb = %d\n",a,b);
return 0;
}
程序输出:
为了理解逻辑,将变量'a'和'b'分别选择为'7'和'9',并按照程序进行。 您也可以选择任何其他数字组合。 有时,这是理解程序的绝佳方式。
C语言交换函数
在这个方法中,我们将创建一个函数来交换数字。 我们将使用 call by reference。
#include <stdio.h>
void swap(int*, int*); //Swap function declaration
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
使用指针交换两个数字
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
C programming code to swap using bit-wise XOR
#include <stdio.h>
int main()
{
int x, y;
scanf("%d%d", &x, &y);
printf("x = %d\ny = %d\n", x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("x = %d\ny = %d\n", x, y);
return 0;
}
排序算法使用交换以升序或降序排列数字。
上一篇:
idea打包java可执行jar包
下一篇:
反转数字的C程序
评论区