1

因此,在我的程序中,我编写了一个函数来查找一组数字的范围,不幸的是它似乎无法正常工作。而不是给我最小数字和最大数字之间的差异,而是给我这个:

(3) Range
(4) Restart/Exit
3
7900455959466841600000000000000000.0

我浏览了整个互联网,虽然我找到了几个有用的例子来说明如何做到这一点,但它们似乎并没有解决这个问题。这是我的功能,如果有人需要查看整个代码,请告诉我。

 float range(float numbers[], int amount)
 {
  int i;
  float diff=0;
  for (i=1;i<=amount;i++){

      diff=numbers[amount]-numbers[1];
  }

      printf("%.1f",diff);

      return diff;
   }

我已经尝试了所有我能想到的,任何建议

4

3 回答 3

2

你想要这样的东西:

float range(float numbers[], int amount)
{
    int i;
    float min, max, diff;
    min = numbers[0];
    max = numbers[0];
    for (i=1; i < amount; i++)
    {
        if (numbers[i] < min) min = numbers[i];
        if (max < numbers[i]) max = numbers[i];
    }

    diff = max - min;

    printf("%.1f",diff);

    return diff;
}
于 2012-10-08T05:53:21.153 回答
1

如果您的数组是有序的,则问题简化为:

/* assuming ammount point to the last position of the array */
return numbers[ammount] - numbers[0]

如果数组未排序,则必须构建一个循环以获取数组的最大和最小元素以返回其差值。

于 2012-10-08T05:57:54.583 回答
0

您的金额变量最好命名为highestIndex

为了修复您的代码,我可以看到您可能会做的两件事:

1)。了解您当前的代码在做什么。尝试“桌面检查”。在纸上(或在您的脑海中)为此功能发明一些输入。

 numbers = [ 2, 17, 4, 10];  amount = 3;

 i = 1, is 1 <=3 ? yes, OK go into the body

 diff = numbers[3] - numbers[1] which is 10 - 17, so diff is now -7

 increment i, i = 2, is 2 <=3 ? yes, OK go into the body

 diff = numbers[3] - numbers[2] which is 10 - 4, so diff is now 6

 increment i, i = 3, is 3 <=3 ? yes, OK go into the body

 diff = numbers[3] - numbers[2] which is 10 - 10, so diff is now 0

 increment i, i = 4, is 3 <=3 ? no. so leave the loop

 print diff ... hmmm it's 0 at the moment

这里的诀窍是选择一个小的示例集,看看处理是否有意义。显然,除非输入数组已排序,否则这永远无法找到范围,但在这种情况下,您需要循环,只需减去 numbers[highestIndex] 和 numbers[0]。

2)。现在你需要做什么?范围是列表中最大数字和最小数字之间的差。因此,您的代码需要查看列表并找到最大和最小的数字。尝试这样开始

初始化候选值,注意如果你的列表只有一个成员这是正确的,那么最大和最小是相同的,列表中唯一的值

  float biggest = numbers[0];
  float smallest = numbers[0];

然后循环查看是否有任何其他数字大于或小于您当前的最大和最小。

  for ( int i = 1; i <= highestIndex; i++ ) {

         is numbers[i] bigger than biggest
               set new biggest value

         do the same sort of thing for smallest

  }

  print biggest - smallest

然后为了获得额外的信用,看看如果所有数字都是负数会发生什么以及在特殊情况下会发生什么,请阅读浮点数可以保持的值。

于 2012-10-08T06:06:15.243 回答