我正在尝试编写一个交换两个数字的程序。我试图修改我的代码,但仍然没有显示答案。请提前提供帮助和感谢。
变量为x、y和z,值为10、-1 和 5。因此:x=10、y=-1 和 z=5。预期的输出必须为x=-1、y=5和z=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/