zoukankan      html  css  js  c++  java
  • C# 二分查找求平方根

           static int Sqrt1(int num)
    {
    if (num < 0)
    {
    throw new Exception(num + " doesn't have square root.");
    }

    if (num == 1)
    {
    return num;
    }
    int low = 0;
    int high = num;
    int temp = (low + high) / 2;
    int sign = temp;
    checked
    {
    while (Math.Abs(temp * temp - num) > 1)
    {
    sign = temp;
    if (temp * temp > num)
    {
    high = temp;
    }
    else
    {
    low = temp;
    }
    temp = (low + high) / 2;
    if (sign == temp)
    {
    break;
    }
    }
    }
    if (temp * temp == num)
    {
    return temp;
    }
    else
    {
    throw new Exception(num + " doesn't have integer square root.");
    }
    }
  • 相关阅读:
    2月11日
    亚特兰蒂斯
    080215 晴
    2月9日
    2月6日
    2月10日
    080208 晴(0,50)
    关于春晚
    (15,50)
    恍然大悟
  • 原文地址:https://www.cnblogs.com/Ligeance/p/2344776.html
Copyright © 2011-2022 走看看