[英]How to find a value in an array that is closest to a given number
I'm trying very hard to understand this concept (arrays), but I'm having so much trouble (it's my first computer science course.) Here is my code, with the problem commented at the top. 我正在努力理解这个概念(数组),但是遇到了很多麻烦(这是我的第一门计算机科学课程。)这是我的代码,问题在顶部。 I've tried to solve this problem, but I don't think my logic is correct because I'm not getting a desired answer.
我已经尝试解决此问题,但是我认为我的逻辑不正确,因为我没有得到想要的答案。
// Generate an array of 50 random numbers between 1 to 100. Now, find the number in the array closest to 75 and output it using println().
int[] numbers = new int[50];
int targetNumber = 75;
for (int i = 0; i < numbers.length; i++){
numbers[i] = (int) random(1,100);
int closestSoFar = abs(numbers[i]-targetNumber);
if(closestSoFar > targetNumber){
closestSoFar = abs(numbers[i]-targetNumber);
println(closestSoFar);
}
}
Whereas I would be VERY grateful for the correct answer, I would LOVE to hear why it's the correct answer, and how going forward I can improve my logic so I can do it on my own in the future. 尽管我非常感谢正确的答案,但我很想听听为什么这是正确的答案,以及我将如何改进自己的逻辑,以便将来自己做得到。
As requested I'll explain what I think the answer is and then some hints on how you could have found it. 根据要求,我将解释我认为答案是什么,然后对如何找到答案提供一些提示。
Your logic is: 您的逻辑是:
int closestSoFar = abs(numbers[i] - targetNumber);
if (closestSoFar > targetNumber) {
Now imagine the number is '76'. 现在想象一下数字是“ 76”。
closestSoFar
will become abs(76 - 75)
which is 1
. closestSoFar
将变为abs(76 - 75)
closestSoFar
abs(76 - 75)
,即1
。 That's clearly not larger than 75
. 显然不大于
75
。
So the logic error is simple: you are comparing a difference to an absolute number. 因此,逻辑错误很简单:您正在将差值与绝对数进行比较。
The resolution is that you really need to check if the current number numbers[i]
is closer than closestSoFar
. 解决方案是,您确实需要检查当前数字
numbers[i]
是否比closestSoFar
更近。 That can be done with: 可以通过以下方式完成:
if (abs(numbers[i] - targetNumber) < abs(closestSoFar - targetNumber)) {
Now, with respect to how you could have found it yourself, here are some tips: 现在,关于您自己如何找到它,这里有一些提示:
isClosestToTarget
and have some unit tests that ensures it does what you expect before moving on to methods that use the already tested methods. isClosestToTarget
的方法,并进行一些单元测试,以确保在继续使用已测试方法的方法之前,它可以达到预期的效果。 int[] numbers = new int[50];
int targetNumber = 75;
int closestDifference = targetNumber;
int closestNumber= 0;
for (int i = 0; i < numbers.length; i++){ numbers[i] = (int) random(1,100);
if(closestDifference > abs(numbers[i]-targetNumber){
closesDifference = abs(numbers[i]-targetNumber);
closestNumber= numbers[i];
}
println(closestNumber);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.