While cycle with conditions never ending
Show older comments
Hi,
I have to simulate dice rolls and count rolls until I got 6 twice in a row. I have this code:
clear all
close all
clc
rng("shuffle");
Dice1 = 0;
Dice2 = 1;
s=0;
while (Dice1&&Dice2)~=6
Dice1 = Dice2;
Dice2 = randi(6);
s=s+1;
end
And it never stops. I believe I have conditon set correctly because when Dice1 and Dice2 are both manually set to 6, I got logical 0. Where is a problem?
Accepted Answer
More Answers (2)
while ~(Dice1==6 & Dice2==6)
The expression as written first does AND operation of the two numeric, not logic, values and then tests that.
Dice1=6; Dice2=Dice1;
Dice1&Dice2
is a logical True, but it isn't ==6 and anything where both operands are nonzero will produce the same result.
Steven Lord
on 27 Aug 2024
while (Dice1&&Dice2)~=6
This line of code doesn't do what you think it does.
(Dice1 && Dice2) is either true (if both Dice1 and Dice2 are non-zero) or false (if either is zero.) True is not equal to 6 and neither is false, so this while condition is always satisfied regardless of the value of (Dice1 && Dice2). Therefore you cannot break out of the loop.
You might think that (Dice1 ~= 6 && Dice2 ~= 6) is the right approach. Try working through it with Dice1 equal to 6 and Dice2 equal to 5. Should the loop repeat in that scenario? Does it?
Write out the condition in words not code and pay attention to the single word conjunction you use to combine the two clauses. "I want the loop to repeat while <blah1> <conjunction> <blah2>". Did you use "and" or "either/or" to combine blah1 and blah2?
1 Comment
Jan
on 6 Sep 2024
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!