【发布时间】:2023-03-23 17:58:01
【问题描述】:
编写一个对三个数字进行排序的程序。用户将输入三个数字 int 变量,名为 num1、num2 和 num3。您将通过引用将这三个值传递给名为 sortNums() 的函数,然后将它们按从小到大的顺序排列。 Num1 将保存最小值,num2 将保存中间值,num3 将保存最大值。从 main() 中按顺序打印数字。
如何修复我的 if 语句。当我输入 123 时,结果正确,当我输入 321 时,结果正确,但当我输入 213 时,结果错误。
//function prototype
void sortNums(int*,int*,int*);
int main()
{
//Variables
int num1;
int num2;
int num3;
//refernce numbers variables
int *one;
int *two;
int *three;
//inputing nums
printf("Please enter num1: \n");
scanf("%d", &num1);
printf("Please enter num2: \n");
scanf("%d", &num2);
printf("Please enter num3: \n");
scanf("%d",&num3);
//putting reference numbers into variables
one = &num1;
two = &num2;
three = &num3;
sortNums(one,two,three);
printf("num1 %d\n",num1);
printf("num2 %d\n",num2);
printf("num3 %d\n",num3);
getch();
return 0;
}
//function
void sortNums(int *one,int *two, int *three)
{
int n1 = *one;
int n2 = *two;
int n3 = *three;
if ((n1 > n2) && (n2 > n3)){
*one = n3;
*two = n2;
*three = n1;
}
else if ((n1 > n2) &&(n2 < n3) ){
*one = n2;
*two = n3;
*three = n1;
}
else {
*one = n1;
*two = n2;
*three = n3;
}
}
【问题讨论】:
-
我看到的唯一问题是您没有完全对它们进行排序。
-
现在检查一下,我的问题在顶部。
-
ifs中不应该是one = &n1之类的吗?