在C#中平均分配 [英] Evenly divide in c#
本文介绍了在C#中平均分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中我如何均分100到7?
In c# how do I evenly divide 100 into 7?
因此,结果将是
- 16
- 14
- 14
- 14
- 14
- 14
- 14
- 16
- 14
- 14
- 14
- 14
- 14
- 14
因为所有的7个值设置为15(共计105)下面的代码是不正确。
The code below is incorrect as all 7 values are set to 15 (totalling 105).
double [] vals = new double[7];
for (int i = 0; i < vals.Length; i++)
{
vals[i] = Math.Ceiling(100d / vals.Length);
}
有没有一种简单的方法在C#这样做吗?
Is there an easy way to do this in c#?
感谢
推荐答案
要得到我的15个建议的结果,15,14,14, 14,14,14:
To get my suggested result of 15, 15, 14, 14, 14, 14, 14:
// This doesn't try to cope with negative numbers :)
public static IEnumerable<int> DivideEvenly(int numerator, int denominator)
{
int rem;
int div = Math.DivRem(numerator, denominator, out rem);
for (int i=0; i < denominator; i++)
{
yield return i < rem ? div+1 : div;
}
}
Test:
foreach (int i in DivideEvenly(100, 7))
{
Console.WriteLine(i);
}
这篇关于在C#中平均分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文