手动平方根代码给出奇怪的输出
本文关键字:输出 平方根 代码 | 更新日期: 2023-09-27 18:17:07
我正在尝试学习c#,我有兴趣尝试写一个简单的do-while来计算一个简单数字的平方根
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;像根+=1;它对偶数的答案非常有效但一旦我开始使用0.1或更小,它就会断裂,甚至忽略了while语句中的检查
谁能解释一下为什么会这样?注意:我不需要解决方案,只需要解释发生这种情况的原因。我知道可以使用math。sqrt (value);
感谢@JonSkeet的回答(以及@PaulHicks的提及)
float和double是浮点二进制类型。换句话说,它们像这样表示一个数字:
10001.10010110011二进制数和二进制点的位置都在值中编码。
decimal是浮点小数点类型。换句话说,它们像这样表示一个数字:
12345.65789
这样做,因此,解决了这个问题:
int x = 4;
decimal root = 0;
do
{
root += 0.0001M;
}
while ((root * root) % x != 0);
Trace.WriteLine(Math.Sqrt(x));
Trace.WriteLine(root);