您的金额变量最好命名为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
然后为了获得额外的信用,看看如果所有数字都是负数会发生什么以及在特殊情况下会发生什么,请阅读浮点数可以保持的值。