Skip to content

Latest commit

 

History

History
78 lines (57 loc) · 1.73 KB

File metadata and controls

78 lines (57 loc) · 1.73 KB

C 程序:使用按引用调用以循环顺序交换数字

原文: https://www.programiz.com/c-programming/examples/swapping-cyclic-order

在此示例中,使用按引用调用以循环顺序交换用户输入的三个数字。

要理解此示例,您应该了解以下 C 编程主题:


按引用调用交换元素的程序

#include <stdio.h>
void cyclicSwap(int *a, int *b, int *c);
int main() {
    int a, b, c;

    printf("Enter a, b and c respectively: ");
    scanf("%d %d %d", &a, &b, &c);

    printf("Value before swapping:\n");
    printf("a = %d \nb = %d \nc = %d\n", a, b, c);

    cyclicSwap(&a, &b, &c);

    printf("Value after swapping:\n");
    printf("a = %d \nb = %d \nc = %d", a, b, c);

    return 0;
}

void cyclicSwap(int *n1, int *n2, int *n3) {
    int temp;
    // swapping in cyclic order
    temp = *n2;
    *n2 = *n1;
    *n1 = *n3;
    *n3 = temp;
} 

输出

Enter a, b and c respectively: 1
2
3
Value before swapping:
a = 1 
b = 2 
c = 3
Value after swapping:
a = 3 
b = 1 
c = 2 

在此,用户输入的三个数字分别存储在变量abc中。 这些数字的地址将传递到cyclicSwap()函数。

cyclicSwap(&a, &b, &c); 

cyclicSwap()的函数定义中,我们已将这些地址分配给了指针。

cyclicSwap(int *n1, int *n2, int *n3) {
    ...
} 

cyclicSwap()内部的n1n2n3改变时,abmain()内部的c也被更改。

注意cyclicSwap()函数未返回任何内容。