如何生成增量为0.50的级数
本文关键字:何生成 | 更新日期: 2023-09-27 18:15:50
我有一串数字,比如1,2,3,4,5,6,7,8,9,10我想生成一个增量为0.5的级数结果应为0.5、1.0、1.5、2.0、2.5、3.0、3.5、4.0、4.5等
是否有简单的数学计算方法?一轮
double x = 0;
while(true) yield return x += 0.5;
对于Math.Round
,这是不可能的。但是:
public static IEnumerable<float> Serie()
{
float val = 0f;
while (true)
{
val += 0.5;
yield return val;
}
}
警告:该方法是有限的,请注意(如果调用ToList()
不是一件好事)。
我认为你不需要math.round
IEnumerable<int> numbers = Enumerable.Range(1, 10);
List<decimal> result = numbers.Select(x => (decimal)x / 2).ToList();
或
List<decimal> result2 = numbers.Select(x => (decimal)x + 0.5m).ToList();
无论你的规则是什么
您可以使用以下方法。这种方法需要一个IEnumerable<int>
作为输入,然后返回一个IEnumerable<double>
,其中一半合并在一起。
IEnumerable<double> GetListWithHalfs(IEnumerable<int> inputList)
{
IEnumerable<double> halfList = inputList.Select(i => i - 0.5);
return inputList.Zip(halfList, (full, half) => new double[] { half, full }).SelectMany(d => d);
}
使用方式:
IEnumerable<int> originalList = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<double> includingHalfs = GetListWithHalfs(originalList);
foreach(var number in includingHalfs)
Console.WriteLine(number);
输出:0 5
1
1、5
2
2、5
3
3、5
4
4、5
5
5、5
6
6、5
7
7、5
8
8、5
9
9、5
10
或者你可以内联所有内容,这样你就可以不用使用方法:
var inputList = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var result = inputList.Zip(inputList.Select(i => i - 0.5), (full, half) => new double[] { half, full }).SelectMany(d => d);