I don't understand how to do this correctly?

2013-12-30 2:07 am
y = 0
x = 3
y = x +y keep doing the iteration if x >0 if x = x - 1
that is, you subtract 1 from x for every iteration until you get to 0


I don't know why I'm not getting this. The answer is 9 by the way.
The attempt at a solution is shown below.

I add 0 and 3,
subtract 1. x is now 2.
then I add 2 and 3. subtract 1 from x. x is now 1
then I add 1 and 5. subtract 1 from x. x is now 0
Now finished with the while statement we go and print y

Basically I am adding x and y to get the new value of y and then repeating

Please explain what I'm doing wrong and how I should be going about it.
更新1:

the answer is 9 because in python, the programming language that i ran this on said that it was. the actual code, if you're interested is y = 0 x = 3 itersLeft = x while (itersLeft 0): y = y x itersLeft = itersLeft - 1 print y

更新2:

there should be a minus sign in between the y and x on line 5

回答 (3)

2013-12-30 2:14 am
✔ 最佳答案
i get y=6 at the end
2013-12-30 10:12 am
I get y = 6 at the end.

What exactly is being iterated?
Is it this:
y = 0; x = 0;
while ( x > 0 ) {
y = x + y;
x = x -1
}
print y;
2013-12-30 10:10 am
first time you go through you get
y = 3.
next time
y = 2+3 = 5
next time
y =1+5 = 6


收錄日期: 2021-04-20 23:56:25
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20131229180714AAQUPeh

檢視 Wayback Machine 備份