C#浮点精度

C#浮点精度,c#,floating-point,C#,Floating Point,试图创建Mandelbrot集时,我一直试图在程序中使用8位和15位浮点变量,但遇到了一个问题:double近似于0。我尝试了单元测试,并编写了这段代码来隔离问题。使用变量查看器,h和w值都在0.0上,而不是0.00185185185185和0.0015625,但是当我只写双h=0.0015625时,它工作正常 非常感谢你的帮助 int apparentwidth = 3; int apparentheight = 2; int height = 1080; int width = 1920;

试图创建Mandelbrot集时,我一直试图在程序中使用8位和15位浮点变量,但遇到了一个问题:
double
近似于
0
。我尝试了单元测试,并编写了这段代码来隔离问题。使用变量查看器,
h
w
值都在
0.0
上,而不是
0.00185185185185
0.0015625
,但是当我只写
双h=0.0015625
时,它工作正常

非常感谢你的帮助

int apparentwidth = 3;
int apparentheight = 2;
int height = 1080;
int width = 1920;

double w = (apparentwidth / width);
double h = (apparentheight / height);

Console.WriteLine(w);
Console.WriteLine(h);

将两个
int
变量相除,结果是
int
。您正在将结果存储在一个
双精度
,但小数点后的比例已经丢失

在整个过程中使用
double

 double apparentwidth = 3;
 double apparentheight = 2;
 double height = 1080;
 double width = 1920;

 double w = (apparentwidth / width);
 double h = (apparentheight / height);
或在除法时将其中一个变量转换为双精度:

 double w = ((double)apparentwidth / width);
 double h = ((double)apparentheight / height);

将两个
int
变量相除,结果是
int
。您正在将结果存储在一个
双精度
,但小数点后的比例已经丢失

在整个过程中使用
double

 double apparentwidth = 3;
 double apparentheight = 2;
 double height = 1080;
 double width = 1920;

 double w = (apparentwidth / width);
 double h = (apparentheight / height);
或在除法时将其中一个变量转换为双精度:

 double w = ((double)apparentwidth / width);
 double h = ((double)apparentheight / height);

你在事故中做整数除法

double w = (double)apparentwidth / (double)width;
double h = (double)apparentheight / (double)height;

你在事故中做整数除法

double w = (double)apparentwidth / (double)width;
double h = (double)apparentheight / (double)height;

为了进一步解释其他答案:

int
s执行数学运算时,结果是
int
,这是通过有效截断非整数部分实现的:

3 / 2 == 1
当执行涉及至少一个
double
的操作时,
int
输入首先转换为
double
,因此结果为
double

1.0 / 4 == 0.25
4 * 0.25 == 1
当然,如果两个输入都是
double
,则结果是
double
,并且不会发生隐式转换:

1.0 / 4.0 == 0.25

为了进一步解释其他答案:

int
s执行数学运算时,结果是
int
,这是通过有效截断非整数部分实现的:

3 / 2 == 1
当执行涉及至少一个
double
的操作时,
int
输入首先转换为
double
,因此结果为
double

1.0 / 4 == 0.25
4 * 0.25 == 1
当然,如果两个输入都是
double
,则结果是
double
,并且不会发生隐式转换:

1.0 / 4.0 == 0.25

正在对整数执行数学运算,然后转换为浮点。您可能希望在进行数学运算之前进行转换。数学运算是在整数上执行的,然后您将转换为浮点。你可能想在做数学之前转换。我不同意使用双精度。这里似乎不需要使用64位数字,除了保留按转换除法的精度。见鬼,根据OP中的内容,一个短片可能就足够了。我不同意使用双通透。这里似乎不需要使用64位数字,除了保留按转换除法的精度。见鬼,根据OP中的内容,一个短片可能就足够了。