0

我在 Matlab 中编写了一个 while 循环,它应该确定参数“n”的值“a”超过值 300。我知道“n”应该是 17,但我得到的值是 4 . 有没有人看到问题?

代码如下:

a = 10;
k = 0.5;
n = 2;
while a < 300
    for m = 1:5
        a = a + (a*k) + n;
    end
    n = n + 1;
end

编辑:感谢 Barmar 的评论,我意识到我没有重新初始化我的“a”变量。尽管代码可能看起来效率不高,但这对我有用:

a = 10;
k = 0.5;
n = 2;
while a < 300
    a = 10;
    for m = 1:5
        a = a + (a*k) + n;
    end
    if a >= 300
        break
    end
    n = n + 1;
end
4

1 回答 1

0

If your formula is correct then 4 is the answer you should expect. The first for loop run turns a into the respsective values:

17, 27, 42, 65, 99

Which then turns n to 3. The next run turns a into:

151, 229, 346, 522, 786

Notice that a is now > 300 but we have to increment n one more time. Thus n = 4.

于 2013-10-18T02:18:44.777 回答