原文: https://www.programiz.com/c-programming/examples/swapping
在此示例中,您将学习使用两种不同的技术在 C 编程中交换两个数字。
要理解此示例,您应该了解以下 C 编程主题:
使用临时变量交换数字
#include<stdio.h>int main() {double first, second, temp;printf("Enter first number: ");scanf("%lf", &first);printf("Enter second number: ");scanf("%lf", &second);// Value of first is assigned to temptemp = first;// Value of second is assigned to firstfirst = second;// Value of temp (initial value of first) is assigned to secondsecond = temp;printf("\nAfter swapping, firstNumber = %.2lf\n", first);printf("After swapping, secondNumber = %.2lf", second);return 0;}
输出
Enter first number: 1.20Enter second number: 2.45After swapping, firstNumber = 2.45After swapping, secondNumber = 1.20
在上述程序中,为temp变量分配了first变量的值。
然后,将second变量的值分配给first变量。
最后,将temp(其保存first)分配给second。 这样就完成了交换过程。
交换数字而不使用临时变量
#include <stdio.h>int main() {double a, b;printf("Enter a: ");scanf("%lf", &a);printf("Enter b: ");scanf("%lf", &b);// Swapping// a = (initial_a - initial_b)a = a - b;// b = (initial_a - initial_b) + initial_b = initial_ab = a + b;// a = initial_a - (initial_a - initial_b) = initial_ba = b - a;printf("After swapping, a = %.2lf\n", a);printf("After swapping, b = %.2lf", b);return 0;}
输出
Enter a: 10.25Enter b: -12.5After swapping, a = -12.50After swapping, b = 10.25
