c - (函数)交换c中的两个数字

标签 c function if-statement swap

我正在尝试编写一个交换两个数字的程序。我试图修改我的代码,但仍然没有显示答案。请提前提供帮助和感谢。

变量为xyz,值为10-15。因此:x=10y=-1z=5。预期的输出必须为x=-1y=5z=10。正如您所看到的,顺序是从最小的数字到最大的数字。。所以请更正我的代码,我使用 Dev-C++ 5.11 作为我的编译器。附:根据我的老师的指示,交换的公式不得更改。 (虽然也许你知道)

这是我编写的代码:

void swap(int *px, int *py)
{
    int temp;
    temp = *px;
    *px = *py;
    *py = temp;
}
int main(void)
{
    int x,y,z;
    x=10;
    y=-1;
    z=5;

    printf("x=%d y=%d z=%d\n",x,y,z);
    if(x>y)
    {
        x=y;
    }
    else if(y>z)
    {
        y=z;
    }
    else if(z>x)
    {
        z=x;
    }
    swap(&x,&y);
    printf("x=%d y=%d z=%d",x,y,z);

    return 0;
}

同样,预期输出必须是:

x=-1, y=5, z=10

最佳答案

我认为你需要这样的东西:

// Make sure x is smaller than y
if(x>y)
{
    swap(&x, &y);
}

// Make sure x is smaller than z
if(x>z)
{
    swap(&x, &z);                      
} 
// Now x is smaller than both y and z

// Make sure y is smaller than z
if(y>z)
{
    swap(&y, &z);
}

所以完整的程序看起来是:

#include <stdio.h>

void swap(int *px, int *py)
{
    int temp;
    temp = *px;
    *px = *py;
    *py = temp;
}
int main(void)
{
    int x,y,z;
    x=10;
    y=-1;
    z=5;

    printf("x=%d y=%d z=%d\n",x,y,z);

    // Make sure x is smaller than y
    if(x>y)
    {
        swap(&x, &y);
    }

    // Make sure x is smaller than z
    if(x>z)
    {
        swap(&x, &z);                      
    } 
    // Now x is smaller than both y and z

    // Make sure y is smaller than z
    if(y>z)
    {
        swap(&y, &z);
    }

    printf("x=%d y=%d z=%d",x,y,z);

    return 0;
}

输出为:

x=10 y=-1 z=5

x=-1 y=5 z=10

关于c - (函数)交换c中的两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971329/

相关文章:

c - 如何在 C 中仅使用 2 个循环和 1 个 if 语句绘制此图?

mysql - 是否有替代的 if-else 语法而不需要 endif

c - 为什么文件意外更改?

c++ - 查找二进制到 C/C++ 的链接

c - 在另一台机器上运行从 clang+llvm 编译的程序

python - 中断并继续功能

无法找出为什么 valgrind 在我的具有结构数组的代码中给出错误

c++ - 哪个更好 : returning tuple or passing arguments to function as references?

javascript - (function() {})() 声明/初始化 javascript 函数

多个 If 条件的 C 缩写形式