【问题标题】:C# - Comparing float valuesC# - 比较浮点值
【发布时间】:2014-03-30 18:40:31
【问题描述】:

我在尝试比较 2 个浮点值时遇到了一点问题。
在我的项目中,每个 Game 对象都有一个 .Score
每个 .Score 属性都有一个介于 0 和 10 之间的浮点值,步长为 0.5
在 minimumscoreId 中存储了一个浮点值 0..11(如果函数未使用,则为 0)
我遍历每场比赛以查看分数是否高于所选分数。但是当我选择 9 作为 minimumScore 时,它​​是 9.5

更奇怪的是,如果我选择 8,它会返回一个游戏的分数为 9,另一个是 9.5,另一个是 7.5...

我真的不知道在哪里寻找这个问题,我尝试停止并检查值,但它只是 if( 9.5 < 9.0 ) 并且它仍然进入 if...

if (minimumScoreId > 0)
    {
        for (int i = 0; i < minimumScoreId; i++)
        {
            float score = ( ((Game)(games[i]) ).Score);
            if ( score < ( minimumScoreId + 1.0) )
            {
                //delete from a list (this works in other functions without the float thing)
            }
        }
    }

【问题讨论】:

  • 您确定要将分数与 minimumScoreId 进行比较吗?
  • 顺便说一句,您的第一个 if 在这里是多余的 - 如果 minumumScoreId 为零(或更少),则 for 循环不会运行。
  • 我怀疑您的“从列表中删除”代码未按预期工作。
  • @AndrewMorton 可能会有所作为。如果您要从位置 igames 删除,那么您需要向后迭代它。
  • 我会考虑在内部使用整数,只转换为浮点数进行显示。

标签: c# comparison


【解决方案1】:
if (minimumScoreId > 0)
                {
                    filter = true;
                    int j = 1;
                    for (int i = 1; i < minimumScoreId; i++)
                    {
                        float score = (((Game)(games[i-1])).Score);
                        if (score < ((float)minimumScoreId + 0.0))
                        {
                            gamesUpdate.RemoveAt(j-1);
                            j--;
                        }
                        j++;
                    }

感谢大家的帮助!最后的2个回复也很有帮助,如果我有额外的时间,我会让迭代倒退。目前我以这种方式解决了它,并且有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多