C#double向下舍入为零

时间:2018-01-11 09:11:51

标签: c# double rounding

我有一些C#代码用于将omnicam图片转换为普通图片。但是,该公式的表现与预期不同。

代码:

  int Rin = 35; //Image specific variable
  int Rout = 237; //Image specific variable
  int cx = 312; //Image specific variable
  int cy = 239; //Image specific variable
  int width = (int) Math.Round(2 * Math.PI * Rout);
  int height = (int) Math.Round((double)(Rout - Rin));
  for (int i = 0; i < image.GetLength(0); i++)
      {
        double y1 = i / height;
        double r = Rin + (1 - y1 * height);
        for (int j = 0; j < image.GetLength(1); j++)
        {
          double x1 = j / width;
          double theta = -2 * Math.PI * (j / width);

          double xp = r * Math.Cos(theta) + cx;
          double yp = r * Math.Sin(theta) + cy;
          Console.WriteLine(theta + " = " + (-2 * Math.PI) + " * (" + j + " / " + width + ")");
          Console.WriteLine(xp + " = " + r + " * " + Math.Cos(theta) + " + " + cx);
          Console.WriteLine(yp + " = " + r + " * " + Math.Sin(theta) + " + " + cy);
          Console.WriteLine("");

          omnicam[i, j] = Color.FromArgb(1, 1, 1);
        }
      }

然而,这打印出来

0 = -6.28318530717959 * (82 / 1489)
348 = 36 * 1 + 312
239 = 36 * 0 + 239

如果我打印x1,则所有值都显示0。但是,我不确定为什么。循环上升到895,并且895/1489 = 0.601 ...那么为什么它会自动向下舍入?

1 个答案:

答案 0 :(得分:0)

double x1 = j / width;

j和宽度都是INT。

double x1 = j /(double)width;

会给你预期的结果。

如果C#中的两个参数都是int,那么结果将是一个int。

如果C#中的任何参数是double,则使用双倍除法,这会导致双倍。