我想学习C#和我很感兴趣,试图写一个简单的做,而如果我使用一个计算简单的数字手动平方根代码给出了奇怪的输出
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double x = Convert.ToDouble(Console.ReadLine());
double root = 0;
do
{
root += 0.0001;
Console.WriteLine(root);
}
while ((root * root) % x != 0);
Console.WriteLine(Math.Sqrt(x));
Console.WriteLine(root);
}
}
}
的平方根根号码= 0.0001;像root + = 1; 它甚至可以很好地解答答案 但是一旦我开始使用0.1或更小的值,它会中断, ,甚至会忽略while语句中的检查。
有人可以解释为什么会发生这种情况吗? 注:我不需要一个解决方案,只是为什么发生这种情况。我知道我可以使用Math.Sqrt(value);
不要使用双,浮法用于浮点数的比较! http://csharpindepth.com/Articles/General/FloatingPoint.aspx – mybirthname
'while((root * root) - xε);'其中'epsilon'是一个足够小的数字可能是一个更好的比较 –