首页 新闻 赞助 找找看

一道递归题的函数

0
悬赏园豆:30 [已解决问题] 解决于 2011-12-05 10:55

我现在有个Dictionary

 

如下:

            Dictionary<string, int> A = new Dictionary<string, int>();
A.Add("电脑",20);
A.Add("键盘", 30);
A.Add("鼠标", 90);
A.Add("显示器", 120);

现在我有2000块钱,

我要轮询地买这些东西,

现在有个函数   

  public int Buy(Dictionary<string,int> A,decimal TotalMoney)

这个函数输入总的钱数,和要买的器件,

就会输出:

买了“电脑”后的:余额为:1000,

买了“鼠标“后的:余额为:200

 

请问这个函数怎么写????!

Buy 函数…………


需要格局的主页 需要格局 | 老鸟四级 | 园豆:2145
提问于:2011-12-04 15:21
< >
分享
最佳答案
0
static void Main(string[] args)
{
Dictionary<String, Int32> productList = new Dictionary<string, int>();
productList.Add("电脑", 20);
productList.Add("键盘", 30);
productList.Add("鼠标", 90);
productList.Add("显示器", 120);
int totalMoney = 2000;
Buy(productList, ref totalMoney);

Console.ReadLine();
}
public static void Buy(Dictionary<String, Int32> _productList, ref Int32 _totalMoney)
{
KeyValuePair<String, Int32> product = _productList.First();
Console.WriteLine(String.Format("正在购买“{0}”,价格为:{1}···", product.Key, product.Value));
_totalMoney -= product.Value;
_productList.Remove(product.Key);
System.Threading.Thread.Sleep(2000);
Console.WriteLine(String.Format("购买“{0}”后,余额为:{1}", product.Key, _totalMoney));
Console.WriteLine(Environment.NewLine);

System.Threading.Thread.Sleep(3000);
if (_productList.Count > 0)
Buy(_productList,ref _totalMoney);
}
收获园豆:30
写代码的小2B | 老鸟四级 |园豆:4371 | 2011-12-05 10:07

强……

需要格局 | 园豆:2145 (老鸟四级) | 2011-12-05 10:55
其他回答(3)
0

你这个需要递归吗?还有就是每件是不是可以购买多次?购买多次也就有很多解了。购买一次,是不是有顺序要求?

小小刀 | 园豆:1991 (小虾三级) | 2011-12-04 19:11

哈……

 

这问题……

其实可以有简单的办法的……

我就是想用递归来解决

支持(0) 反对(0) 需要格局 | 园豆:2145 (老鸟四级) | 2011-12-04 20:16
0

需求描述的不够清楚,能不能详细描述一下购买的规则呢?

胡屯 | 园豆:714 (小虾三级) | 2011-12-05 09:08
0

模仿一下“背包问题”

船长&CAP | 园豆:318 (菜鸟二级) | 2012-06-07 16:58

看你的描述,不是递归啊

支持(0) 反对(0) 船长&CAP | 园豆:318 (菜鸟二级) | 2012-06-07 16:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册