交换两个数字的 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 temp
      temp = first;

      // Value of second is assigned to first
      first = second;

      // Value of temp (initial value of first) is assigned to second
      second = temp;

      // %.2lf displays number up to 2 decimal points
      printf("\nAfter swapping, firstNumber = %.2lf\n", first);
      printf("After swapping, secondNumber = %.2lf", second);
      return 0;
}

输出

Enter first number: 1.20
Enter second number: 2.45

After swapping, first number = 2.45
After swapping, second number = 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_a
    b = a + b;

    // a = initial_a - (initial_a - initial_b) = initial_b
    a = b - a;

​​​​    // %.2lf displays number up to 2 decimal points
    printf("After swapping, a = %.2lf\n", a);
    printf("After swapping, b = %.2lf", b);
    return 0;
}

输出

Enter a: 10.25
Enter b: -12.5
After swapping, a = -12.50
After swapping, b = 10.25