我想學習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'是一個足夠小的數字可能是一個更好的比較 –