gpt4 book ai didi

C编程,if语句(大到小整数交换)

转载 作者:行者123 更新时间:2023-11-30 19:13:44 26 4
gpt4 key购买 nike

我一直在努力获取代码,将 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...");
}
}

最佳答案

当您执行以下操作时:if (numberTwo>numberOne),您正在比较指针。您需要比较这些指针后面包含的值。这样做: if (*numberTwo>*numberOne)

关于C编程,if语句(大到小整数交换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com