我一直在努力获取代码,以便按升序然后降序排列3个数字。但是,代码会跳过if语句并假定数字是有序的。这是我第一次在C中使用if语句和第二天学习指针,所以任何帮助都会受到赞赏。谢谢
#include<stdio.h>
void swap(int *, int *, int *);
int main(void){
printf("Please enter the first number to sort: ");
scanf("%d",&numberOne);
printf("Please enter the second number to sort: ");
scanf("%d",&numberTwo);
printf("Please enter the third number to sort: ");
scanf("%d",&numberThree);
//swap
swap(&numberOne, &numberTwo, &numberThree);
//return results
printf("The three numbers in descending order is: %d, %d, %d",
numberOne, numberTwo, numberThree);
printf("THe three numbers in ascending order is: %d, %d, %d",
numberThree, numberTwo, numberOne);
}
void swap(int *numberOne, int *numberTwo, int *numberThree){
if (numberOne>numberTwo){
if (numberTwo<numberThree){
int temp =*numberTwo;
*numberTwo=*numberThree;
*numberThree = temp; }
// "312"
else if (numberTwo>numberOne){
if (numberOne>numberThree){
int temp =*numberOne;
*numberOne =*numberTwo;
*numberTwo= temp;
// "231"
}
else if(numberOne<numberThree){
if(numberTwo>numberThree){
int temp =*numberOne;
*numberOne =*numberTwo;
*numberTwo =*numberThree;
*numberThree = temp;
// "132"
}
}
}
else if (numberThree > numberOne){
if (numberTwo< numberOne){
int temp =*numberThree;
*numberThree =*numberTwo;
*numberTwo =*numberOne;
*numberOne = temp;
// "213"
}
else {
int temp = *numberThree;
*numberThree = *numberOne;
*numberOne = temp;
// "123"
}
}
}
else{
printf("Look at that these numbers were in order...");
}
}
答案 0 :(得分:1)
执行此操作时:if (numberTwo>numberOne)
,您正在比较指针。而且你需要比较这些指针背后的值。所以:if (*numberTwo>*numberOne)
答案 1 :(得分:0)
void swap(int *numberOne, int *numberTwo, int *numberThree){
int tmp;
if(*numberOne > *numberThree ){
tmp = *numberThree;
*numberThree = *numberOne;
*numberOne = tmp;
}
if(*numberTwo > *numberThree ){
tmp = *numberThree;
*numberThree = *numberTwo;
*numberTwo = tmp;
}
if(*numberOne > *numberTwo ){
tmp = *numberTwo;
*numberTwo = *numberOne;
*numberOne = tmp;
}
}