Reputation: 23
I'm confused on loops.
I want this MATLAB while loop to stop when the p inside the loop becomes the same as the initial p. Obviously I can't have p ~= p otherwise the loop won't start, so how would I do this as the original p is used for calculations inside the loop
e.g if p=18 I want to use that to calculate a and the next p I'll use in the while loop but I want the while loop to stop when 18 is that next p
p = input(prompt1)
q = input(prompt2)
while(??? ~= p)
a =floor((10*p)/q)
p= (10*p) -(an*q)
end
Upvotes: 0
Views: 44
Reputation: 25490
There is no p
inside the loop and p
outside the loop. There is only one p
. If you want, set p_original = p;
before the loop. Then, make the loop an infinite loop, check the condition at the end, and break out if the condition is satisfied.
p = input(prompt1);
q = input(prompt2);
p_original = p;
while 1
a = floor((10*p)/q);
p = (10*p) - (an*q);
if p == p_original
break;
end
end
If you don't want to have that infinite loop, add a variable that keeps track of whether or not you have looped once. Inside the loop, set it to false
.
first_loop = true;
while p ~= p_original | first_loop
a = floor((10*p)/q);
p = (10*p) - (an*q);
first_loop = false;
end
Upvotes: 1