Skip to main content
 首页 » 编程设计

C#递归以获得正确的计数

2024年02月23日16birdshome

好吧,今天是我大脑无法正常工作的日子之一。
我不能让它工作(:

class Program 
{ 
    static private List<KeyValuePair<int, double>> _list; 
    static protected List<KeyValuePair<int, double>> list 
    { 
        get 
        { 
            if (_list == null) 
            { 
                _list = new List<KeyValuePair<int, double>>(); 
 
                _list.Add(new KeyValuePair<int, double>(1, 11.60));                                         
                _list.Add(new KeyValuePair<int, double>(2, 11.20)); 
                _list.Add(new KeyValuePair<int, double>(3, 13.00)); 
                _list.Add(new KeyValuePair<int, double>(4, 13.60)); 
                _list.Add(new KeyValuePair<int, double>(5, 15.90)); 
                _list.Add(new KeyValuePair<int, double>(6, 16.10)); 
                _list.Add(new KeyValuePair<int, double>(7, 19.10)); 
                _list.Add(new KeyValuePair<int, double>(8, 19.10)); 
                _list.Add(new KeyValuePair<int, double>(9, 19.10)); 
                _list.Add(new KeyValuePair<int, double>(10, 21.00)); 
                _list.Add(new KeyValuePair<int, double>(11, 23.00)); 
            } 
 
            return _list; 
        } 
    } 
 
    static void Main(string[] args) 
    { 
        Program p = new Program(); 
 
        int value = 27; 
        double d = p.GetCost(value); 
    } 
 
    public double GetCost(int tot) 
    { 
        double cost = 0; 
        if (tot < 1) 
            return list[tot-1].Value; 
 
        cost += GetCost(tot - list.Count); 
        return cost; 
    }         
} 

所以从概念上讲,我需要设置递归 GETCOST 过程才能正常工作 这样它就会调用自己并从 LIST 中获取正确的值(第二列) 并将其添加到递归调用方。

预期结果

if the "value" is 8 the total should be $19.10 $19.10 from KeyParValue(8 - 19.10)

if the "value" is 12 the total should be $36.60 $23 + 11.60 from KeyParValue(11 - 23.00) + KeyParValue(1 - 13.60)

if the "value" is 27 the total should be $61.90
$23 + $23 + $15.90; from KeyParValue(11 - 23.00) + KeyParValue(11 - 23.00) + KeyParValue(5 - 15.90)

感谢先进, F.

请您参考如下方法:

这是有问题的:

if (tot < 1) 
    return list[tot-1].Value; 

如果 tot 小于 1,则 tot - 1 小于零,list[tot - 1] 将抛出一个异常。

你真的想要:

if (tot < 1) 
    return list[tot].Value - 1; 

?请注意,这仍然只有在 tot 为 0 时才有效...

我不太清楚您的代码首先要实现什么 - 但我强烈怀疑不使用递归会更清楚。或许您可以描述一下您正在尝试做什么?