for (iy = 0; iy < h; iy++)
{
double angy = (camera.fov_y / h) * iy;
for (ix = 0; ix < w; ix++)
{
double angx = (camera.fov_x / w) * ix;
//output[ix,iy].r = (int)Math.Round(255 * (angy / camera.fov_y);
//output[ix,iy].b = (int)Math.Round(255 * (angy / camera.fov_y);
double tr = (angx / camera.fov_x) * 255D;
double tb = (angy / camera.fov_y) * 255D;
Console.Write("({0},{1})",Math.Round(tr),Math.Round(tb));
output.SetPixel(ix, iy, Color.FromArgb(Convert.ToInt32(tr), 0, Convert.ToInt32(tb)) );
Console.Write(".");
}
Console.WriteLine();
}任何人都能看到该代码有什么直接的问题吗?变量tr和tb的值始终为0。
如果需要的话,我很乐意提供更多的信息。
发布于 2009-04-05 08:31:37
您还没有给出其他变量的类型-特别是camera.fov_x和camera.fov_y的类型是什么?如果它们都是整数,那么初始化angx和angy的行将使用整数算术进行计算。
这可以通过强制转换其中一个操作数来解决:
double angy = ((double) camera.fov_y / h) * iy;虽然fovy和fovx变量已经是双精度的,但这不是问题所在。
你能给出一个完整的例子,我们可以自己编译和测试吗?
编辑: Koistya Navin的编辑太夸张了。你只需要一个表达式的一个操作数是双精度的,整个事情就可以用双精度算术来计算。(但它需要是正确的表达式-如果执行(a/b) * c并将c转换为double,则乘法将使用双精度算术完成,但a/b可能仍然是整数。)
下面的清单做了适当的修改,以确保在应该使用的任何地方都使用了双精度算术:
// Changed loops to declare the variable, for stylistic purposes
for (int iy = 0; iy < h; iy++)
{
// Changed here - cast camera.fov_y
double angy = ((double) camera.fov_y / h) * iy;
for (int ix = 0; ix < w; ix++)
{
// Changed here - cast camera.fov_x
double angx = ((double) camera.fov_x / w) * ix;
//output[ix,iy].r = (int)Math.Round(255 * (angy / camera.fov_y);
//output[ix,iy].b = (int)Math.Round(255 * (angy / camera.fov_y);
double tr = (angx / camera.fov_x) * 255D;
double tb = (angy / camera.fov_y) * 255D;
Console.Write("({0},{1})", Math.Round(tr), Math.Round(tb));
output.SetPixel(ix, iy, Color.FromArgb(Convert.ToInt32(tr),
0,
Convert.ToInt32(tb)) );
Console.Write(".");
}
Console.WriteLine();
}发布于 2009-04-06 10:44:04
它知道这不是您原始问题的一部分,但使用SetPixel(..)效率不是很高,如果您计划在光线跟踪引擎中使用它,可能会出现问题。
您可能希望使用LockBits()方法,有关更多详细信息,请参阅此answer和this one。他们的另一种方法是使用“不安全”的C#代码访问数据,这允许您使用指向数据的指针。有关更多信息,请参阅this question,我通过使用“不安全”代码获得了~x2的加速。
发布于 2009-04-05 08:27:50
别忘了把你的整数转换成双精度。例如:
for (iy = 0; iy < h; iy++)
{
double angy = ((double) camera.fov_y / h) * iy;
for (ix = 0; ix < w; ix++)
{
double angx = ((double) camera.fov_x / (double) w) * (double) ix;
output[ix,iy].r = (int) Math.Round(255 * (angy / camera.fov_y);
output[ix,iy].b = (int) Math.Round(255 * (angy / camera.fov_y);
double tr = (angx / camera.fov_x) * 255D;
double tb = (angy / camera.fov_y) * 255D;
Console.Write("({0},{1})",Math.Round(tr), Math.Round(tb));
output.SetPixel(ix, iy, Color.FromArgb(
Convert.ToInt32(tr), 0, Convert.ToInt32(tb)) );
Console.Write(".");
}
Console.WriteLine();
} 快速参考:
int * double = double
int / double = double
double * int = double
double / int = double
int * int = int
int / int = int // be carefull here!
1 / 10 = 0 (not 0.1D)
10 / 11 = 0 (not 1)
1D / 10 = 0.1D
1 / 10D = 0.1D
1D / 10D = 0.1Dhttps://stackoverflow.com/questions/718577
复制相似问题