编写一个程序,对三个数字进行排序。用户将输入名为 num1、num2 和 num3 的三个数字 int 变量。您将通过引用将这三个值传递给一个名为 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;
}
}
最佳答案
您缺少一些 if 测试。
例如,您不会在中间测试中检查 n1 是否大于 n3 或更小。例如,在中间 if 中添加一个 if 将对第二高和最高值进行排序。
如果第一个数字大于第二个数字但小于第三个数字,您也将错过测试。
if ((n1 > n2) && (n2 > n3)){
*one = n3;
*two = n2;
*three = n1;
}
else if ((n1 > n2) &&(n2 < n3) ){
if(n1 > n3) {
*one = n2;
*two = n3;
*three = n1;
} else {
*one = n2;
*two = n1;
*three = n3;
}
} else if(n1 < n2) && (n2 > n3) {
if(n1 > n3) {
*one = n3;
*two = n1;
*three = n2;
} else {
*one = n1;
*two = n3;
*three = n2;
}
} else {
*one = n1;
*two = n2;
*three = n3;
}
添加这些额外的 if's 应该可以解决这个问题。
如果需要,您也可以删除一些 if,但使用不同的 if 语句会使代码更短。您还可以执行其他各种操作来改进代码。例如,您不需要从整数创建指针然后发送它。你可以只做 sortNums(&num1,&num2,&num3);
关于c指针引用和取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22587417/