我正在学习编程,你能帮助我并告诉我出了什么问题吗? 程序应识别最小值,中间值和最大值,并按顺序将其分配给d1,d2,d3
void three_function(double * pnt_d1, double * pnt_d2, double * pnt_d3){
double smallest, middle, largest;
largest = *pnt_d1;
smallest = *pnt_d2;
middle = *pnt_d3;
if (*pnt_d2 > largest)
largest = *pnt_d2;
else if (*pnt_d3 > largest)
largest = *pnt_d3;
else if (*pnt_d1 < smallest)
smallest = *pnt_d1;
else if (*pnt_d3 < smallest)
smallest = *pnt_d3;
else if ((*pnt_d1 > smallest) && (*pnt_d1 < largest))
middle = *pnt_d1;
else if((*pnt_d2 > smallest) && (*pnt_d2 < largest))
middle = *pnt_d2;
*pnt_d1 = smallest;
*pnt_d2 = middle;
*pnt_d3 = largest;
}
执行不力:
Please enter 3 double values: 1 2 3
(开始时) 现在d1 = 1.000000,d2 = 2.000000,d3 = 3.000000
(三功能后) 现在d1 = 2.000000,d2 = 3.000000,d3 = 2.000000
答案 0 :(得分:3)
基本上,如果以下if
成功,则不会执行任何其他语句,因为它们位于else if
中。因此,您要删除所有else
,只需检查if(condition)
6次。像
if (*pnt_d2 > largest)
largest = *pnt_d2;
if (*pnt_d3 > largest)
largest = *pnt_d3;
....
答案 1 :(得分:2)
问题在于:
if (*pnt_d2 > largest) // 2 > 1
largest = *pnt_d2; // largest = 2
else if...
由于else if
代码跳转:
*pnt_d1 = smallest; // not changed and equal to 2
*pnt_d2 = middle; // not changed and equal to 3
*pnt_d3 = largest; // updated by 'if' and equal to 2