简体   繁体   English

C#为什么我的DECIMAL否定?

[英]c# why is my DECIMAL negative?

here is how i call the following function: 这是我如何调用以下功能:

    List<decimal> numbers = new List<decimal>();

    numbers.Add(210m);
    numbers.Add(188.83m);
    numbers.Add(67.93m);
    numbers.Add(125.92m);
    numbers.Add(35.92m);
    numbers.Add(19.16m);
    numbers.Add(98.48m);



    List<decimal> listresult = FindSumSubset(9075.12m, numbers);

** * ** * ** * *** the function * ** * ** * ** * *** 功能 *

List<decimal> FindSumSubset(decimal sum, List<decimal> list)
            {
               for (int i = 0; i < list.Count; i++)
               {
                  decimal value = list[i];
                  if (sum - value == 0.0m)
                  {
                      return new List<decimal> { value };
                  }
                  else
                  {
                      var subset = FindSumSubset(sum - value, list.GetRange(i + 1, list.Count-1 -i));
                      if (subset != null)
                      {
                          subset.Add(value);
                          return subset;


                      }
                  }
               }
               return null;
            }

when i run in debug mode, the decimal sum is giving me a huge negative value like -93435.34 当我在调试模式下运行时, decimal sum给了我一个巨大的负值,如-93435.34

how can this be happening? 怎么会这样呢?

Try making this change: 尝试进行以下更改:

if (sum - value <= 0.0m)

The problem is that sum-value is not exactly 0 so it just keeps recursing forever. 问题在于sum-value并非完全为0,因此它会永远保持递归。

Also, I think you want to remove the for loop. 另外,我认为您想删除for循环。 You don't need it if you recurse. 如果您递归,则不需要它。

你满溢而未检查是我的猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM