#include <stdio.h>
int main() {
int a, b,c;
/* Input a and b */
scanf("%d %d %d", &a, &b,&c);
while(a != -1) {
int *x = &a;
int *y = &b;
int *z = &c;
printf("Original inputs: a:%d\tb:%d\tc:%d\n", a, b,c);
reorder(a,b,c);
swap(a,b);
printf("Rearranged inputs: a:%d\tb:%d\tc:%d\n\n", a, b,c);
break;
}
}
void reorder(int *x, int *y, int *z){
if(*x > *y)
{
int temp = *x;
*x = *y;
*y = temp;
}else if(*y > *z){
int temp = *y;
*y = *z;
*z = temp;
}else if(*x > *z){
int temp = *x;
*x = *z;
*z = temp;
}
}
void swap(int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
我是C新手并且学习指针我不确定如何实现指针以升序交换3个数字
答案 0 :(得分:0)
这可能会给你一个开始的方法:
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void reorder(int* x, int* y, int* z) {
if (*x > *y) {
swap(x, y);
}
if (*y > *z) {
swap(y, z);
}
if (*z > *x) {
swap(z, x);
}
}
int main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
int *x = &a;
int *y = &b;
int *z = &c;
reorder(x, y, z);
}
答案 1 :(得分:0)
您可以出于以下目的使用此代码:
#include <stdio.h>
void reorder(int *, int *, int *);
void swap(int *, int *);
void main()
{
int a, b, c;
printf("Enter three numbers : ");
while (scanf("%i %i %i", &a, &b, &c)==3)
{
reorder(&a, &b, &c);
printf("Now a is %d, b is %d and c is %d.\n\n", a, b, c);
printf("Enter three numbers : ");
}
}
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void reorder(int* a, int* b, int* c) {
if (*c<*a&&*c<*b)
swap(a, c);
if (*b<*a&&*b<*c)
swap(a, b);
if (*c<*b)
swap(b, c);
}