该程序基本上找到给定数字的平方根的近似值.我不明白为什么它不起作用的问题.该程序正在编译但从未运行.它无限地计算一些东西.
public static void Main(string[] args)
{
Console.WriteLine("Enter number to find Square Root");
var num = Convert.ToInt32(Console.ReadLine());
var ans = SqaureRoot(num);
Console.WriteLine("Square root of {0} : {1}",num,ans);
}
Run Code Online (Sandbox Code Playgroud)
问题显然必须在这个方法中,在我看来,代码不会从while循环中退出,我只是看不出原因.必须使用Newton Raphson方法解决此问题仅接近平方根.可能是因为牛顿拉夫森方程没有括号吗?
public static double SqaureRoot(double a)
{
if (a < 0)
throw new Exception("Can not sqrt a negative number");
double error = 0.00001;
double x = 1;
while (true)
{
double val = x * x;
if (Math.Abs(a) <= error)
return x;
x = x / 2 + a / (2 …Run Code Online (Sandbox Code Playgroud) c# ×1