【问题标题】:c pointers referencing and dereferencingc 指针引用和解除引用
【发布时间】: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之类的吗?

标签: c pointers


【解决方案1】:

你缺少一些 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 应该可以解决它。

您也可以根据需要删除一些 if,但使用不同的 if 语句会使代码更短。您还可以做各种其他事情来改进代码。例如,您不需要从整数创建指针然后发送它。你可以这样做sortNums(&amp;num1,&amp;num2,&amp;num3);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2015-02-13
    • 2020-08-19
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多