给定一个起始数,想象一下它的连续两半的无限序列。
1, 0.5, 0.25, 0.125, ...
(忽略任何固有的数值不稳定性double
.)
这可以在单个表达式中完成,而无需编写任何自定义扩展方法或生成器方法吗?
我不知道单表达式方式,但我在这里找到了这个聪明的生成器代码:http://csharpindepth.com/articles/Chapter11/StreamingAndIterators.aspx http://csharpindepth.com/articles/Chapter11/StreamingAndIterators.aspx
public static IEnumerable<TSource> Generate<TSource>(TSource start,
Func<TSource,TSource> step)
{
TSource current = start;
while (true)
{
yield return current;
current = step(current);
}
}
在你的情况下你会使用它:
foreach (double d in Generate<double>(1, c => c / 2))
{
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)