指针和与C的交换

时间:2016-04-13 16:32:52

标签: c

我对如何执行此操作有一个大概的了解,正如您在下面的代码中所看到的那样。我唯一的问题是完成交换部分。基本上,我要做的是将最低变量的值移动到第一个变量,将第二个中间值移动到第二个变量,将最大变量移动到第三个变量。

我知道我这样做是为了交换并以某种方式使用temp,但是如何完成它,因为有三个值temp会以某种方式被覆盖。我错过了什么?所以基本上a = 4.0, b = 7.0, c = 1.0c (1.0)需要进入aa (4.0)需要进入b,而b (7.0)需要进入c 1}}。 谢谢!

#include <stdio.h>
void interchange(double * x, double * y, double * z);

int main(void)
{
  double a = 4.0, b = 7.0, c = 1.0;

  printf_s("Originally a = %d, b = %d, and c = %d.\n", a, b, c);
  interchange(&a, &b, &c);
  printf_s("Now, a =  %d, b = %d, and c = %d.\n", a, b, c);

  return 0;

}

void interchange(double * x, double * y, double * z)
{
  double temp;

  temp = *z;
  *y = *z;
  * = temp 

    // what am I missing here? I cant get my head around this above ^^^

}

感谢您的指导!

2 个答案:

答案 0 :(得分:2)

类似的东西:

void swap(double* first, double* last){
  double temp = *first;
  *first = *last;
  *last = temp;
}

void interchange(double * x, double * y, double * z){
  if(*x > *y) swap(x, y);
  if(*y > *z) swap(y, z);
  if(*x > *y) swap(x, y);
}

答案 1 :(得分:1)

最简单的方法是:

if (*x > *y) {
    temp = *x; // store value of x
    *x = *y; // overwrite x with y
    *y = temp; // overwrite y with x (which is in temp)
}
// now we sure that x <= y
if (*y > *z) {
    temp = *z;
    *z = *y;
    *y = temp;
}
// now we sure that x <= z and y <= z, but we don't know x/y relationships
if (*x > *y) {
    temp = *x;
    *x = *y;
    *y = temp;
}
// now x <= y <= z