double と integer を含む欠陥のある 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
を初期化する行は、整数演算を使用して評価されます。
このオペランドの1を鋳造することにより固定することができます:
double angy = ((double) camera.fov_y / h) * iy;
fovy
とfovx
変数がすでにあるけれども、これは問題ではありません倍増ます。
あなたは私たちが自分自身をコンパイルしてテストすることができ、これの完全な例を挙げてもらえますか?
EDIT:Koistyaナビーンの編集はやり過ぎです。あなただけの、二重計算を用いて計算することが全体のことのために、二重であることを表現の一つのオペランドを必要としています。 (これは、しかし、右の式にする必要がある - あなたが(a/b) * c
を行うとc
ダブルを唱えた場合、乗算は二重の算術演算で行われますが、/ 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