두 배와 정수와 관련된 C# 코드에 결함이 있습니다
문제
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으로 평가합니다.
필요한 경우 더 많은 정보를 제공하게되어 기쁩니다.
해결책
다른 변수의 유형을 제공하지 않았습니다. 특히 유형은 무엇입니까? camera.fov_x
그리고 camera.fov_y
? 둘 다 정수 인 경우 선이 초기화됩니다 angx
그리고 angy
정수 산술을 사용하여 평가됩니다.
이것은 피연산자 중 하나를 캐스팅하여 고정 될 수 있습니다.
double angy = ((double) camera.fov_y / h) * iy;
그만큼 fovy
그리고 fovx
변수는 이미 두 배로이지만 문제가되지 않습니다.
우리가 스스로 컴파일하고 테스트 할 수있는 완전한 예를 제시 할 수 있습니까?
편집 : Koistya Navin의 편집은 과잉입니다. 이중 산술을 사용하여 전체를 계산하기 위해 표현식의 하나의 피연산자 만 두 배로 만 있으면됩니다. (그래도 올바른 표현이어야합니다. (a/b) * c
그리고 캐스트 c
이중, 곱셈은 이중 산술로 수행되지만 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();
}
다른 팁
정수를 두 배로 던지는 것을 잊지 마십시오. 예를 들어:
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.1D
제휴하지 않습니다 StackOverflow