【问题标题】:Getting incorrect output in C# when dividing two decimals在 C# 中除以两位小数时得到不正确的输出
【发布时间】:2019-11-30 10:09:49
【问题描述】:

我有一个程序将一个变量与另一个变量相除。 但是我得到的答案是错误的!!! 请查看下面的图片:

代码如下:

      iter_defects++;
      df1[iter_defects].blob_id = b.Id;
      decimal convertX = Convert.ToDecimal(txtmmtopixX.Text);
      decimal convertY = Convert.ToDecimal(txtmmtopixY.Text);
      df1[iter_defects].count = iter_defects;

      df1[iter_defects].cog_X = Math.Round( Convert.ToDecimal( b.Centroid.X)) / convertX;
      df1[iter_defects].cog_Y = Math.Round(Convert.ToDecimal(b.Centroid.Y ))/ convertY;
     if (df1[iter_defects].cog_X > 10 && df1[iter_defects].cog_X < 30)
      {

     if (df1[iter_defects].BY > 1 && df1[iter_defects].BY < 74)
      {
       df1[iter_defects].cog_X = df1[iter_defects].cog_X - 20;

       }

      if (df1[iter_defects].BY > 64 && df1[iter_defects].BY < 129)
        {
         df1[iter_defects].cog_X = df1[iter_defects].cog_X - 20;

         }

      if (df1[iter_defects].BY > 118 && df1[iter_defects].BY < 183)
         {
           df1[iter_defects].cog_X = df1[iter_defects].cog_X - 20;

         }

       }

b.centroid.X 和 b.centroid.Y 默认为 double,所以我将其转换为十进制。

如果我将 147 除以 9.3,我应该得到大约 16,但我得到 7.9!

之前我使用的是双精度而不是十进制,但即使是十进制也会出现同样的问题。已将变量值固定在右侧图像上。

可能出了什么问题?

更新:

在我的嵌套 if 语句中,我基于少数几个条件进行了一些算术运算。当我删除这些条件时,计算就很好了。现在更迷茫了。下面的代码可以工作,但没有这些条件,我在本节之后的代码将无法工作:

  iter_defects++;
  df1[iter_defects].blob_id = b.Id;
  decimal convertX = Convert.ToDecimal(txtmmtopixX.Text);
  decimal convertY = Convert.ToDecimal(txtmmtopixY.Text);
  df1[iter_defects].count = iter_defects;

  df1[iter_defects].cog_X = Math.Round( Convert.ToDecimal( b.Centroid.X)) / convertX;
  df1[iter_defects].cog_Y = Math.Round(Convert.ToDecimal(b.Centroid.Y ))/ convertY;
 if (df1[iter_defects].cog_X > 10 && df1[iter_defects].cog_X < 30)
  {
  df1[iter_defects].cog_X = df1[iter_defects].cog_X - 20;
  }

【问题讨论】:

  • 不要将代码显示为图像!!
  • 我正在显示变量的值,已将其固定在右侧。
  • 我知道。尝试复制时难以阅读且无用..
  • 1) 邮政编码作为文本而不是图像。 2)如果不正确,什么是正确的?
  • 已将代码更新为带有图像的文本。 147 / 9.3 应该是 16,我在程序中得到 7.9。

标签: c# .net visual-studio mathematical-optimization division


【解决方案1】:

尚不完全清楚您的程序是如何工作的,但我认为问题可能是因为您处于某种循环中,并且当您检查结果时,已经发生了不止一次迭代,并且基值(例如cog_X) 已更改,因此您的比较数学将不匹配。

【讨论】:

    猜你喜欢
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2016-05-30
    • 2017-06-28
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多