[英]Attempting to create a binary search square root calculator, receiving 0 as a result every time
我对Java极为陌生,目前在我的第一堂课中。 我的任务是创建一个二进制搜索平方根计算器。 我相信我的方法和语法基本上都是正确的,尽管由于某种原因,无论我在程序中输入了多少数字,我都会收到0。 谁能告诉我我的计算方法出了什么问题?
public static double calculation(double userInput, double lowerBound, double upperBound, double midPoint) {
// Workaround method to calculate the square root of a double integer value, with the use of two bounds getting infintely closer to a fixed point (the square root).
midPoint = (lowerBound + upperBound) / 2;
upperBound = userInput;
while(midPoint*midPoint - userInput > 0.001 || midPoint*midPoint - userInput < -0.001)
{
if (midPoint*midPoint > userInput)
{
lowerBound = midPoint;
}
else if (midPoint*midPoint < userInput)
{
upperBound = midPoint;
}
}
midPoint = (lowerBound + upperBound) / 2;
return midPoint;
}
这是我对该网站的第一篇真实帖子,对于我的格式有任何不正确之处,我深表歉意。 任何帮助将不胜感激。 如果需要的话,我可以提供更多代码行,尽管林先生认为解决方案仅适用于此部分。 谢谢!
当执行进入while
循环时,它将永远不会退出,因为midPoint
不会在循环体内改变,因此循环条件将永远为真。 我认为您想将此行添加为循环中的最后一条语句:
midPoint = (lowerBound + upperBound) / 2;
另一个错误是循环条件实际上没有任何意义。 我不认为midPoint
是指范围内去(-0.001, 0.001)
我认为您的意思是:
while(midPoint*midPoint - userInput > 0.001 || midPoint*midPoint - userInput < -0.001)
通过这两个更改,您的程序应终止并按预期工作。
在计算中点时,没有理由将中点作为参数传递。 删除它,并将midPoint
设为局部变量。
您正在将midPoint的平方与0.001
和-0.001
进行比较,而不是将这些常量用作对userInput
调整。 这将使答案为0
。 尝试以下方法:
while(midPoint*midPoint > userInput + 0.001 || midPoint*midPoint < userInput - 0.001)
if (midPoint*midPoint > userInput)
{
lowerBound = midPoint;
}
else if (midPoint*midPoint < userInput)
{
upperBound = midPoint;
}
midPoint
。 midPoint = (lowerBound + upperBound) / 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.