反正有没有以指数方式迅速增加? [英] is there anyway to increment exponentially in swift?
问题描述
我正在尝试编写一个for循环,在该循环中我必须按指数递增.我正在使用 stride
函数,但无法正常工作.这是c ++代码,我正在尝试编写一个快速版本.
I am trying to write a for loop, where I have to increment exponentially. I am using stride
function but it won't work.
Here's c++ code, I am trying to write a swift version.
for(int m = 1; m< =高-低; m = 2 * m){}
您能帮我,快速编写这段代码吗?
can you help me, to write this code in swift version?
推荐答案
while循环可能是最简单的解决方案,但这是另一种选择:
A while-loop is probably the simplest solution, but here is an alternative:
for m in sequence(first: 1, next: { 2 * $0 }).prefix(while: { $0 <= high - low }) {
print(m)
}
sequence()
(延迟)生成序列1、2、4,...和 prefix(while:)
将序列限制为给定范围.
sequence()
(lazily) generates the sequence 1, 2, 4, ..., and prefix(while:)
limits that sequence to the given range.
此方法的一个小优势是 m
仅在循环内部声明(这样以后就不会意外使用了),这是一个 constant ,因此这样就不会在循环内无意中对其进行修改.
A slight advantage of this approach is that m
is only declared inside the loop (so that it cannot be used later accidentally), and that is is a constant so that it cannot be inadvertently modified inside the loop.
这篇关于反正有没有以指数方式迅速增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!