While cycle with conditions never ending
1 view (last 30 days)
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?
0 Comments
Accepted Answer
Piyush Kumar
on 27 Aug 2024
@Jan,
It looks like there’s a small issue with the condition in your while loop. The condition (Dice1 && Dice2) ~= 6 is not checking if both Dice1 and Dice2 are equal to 6. Instead, it’s checking if the logical AND of Dice1 and Dice2 is not equal to 6, which is not what you want.
You should change the condition to check if both Dice1 and Dice2 are equal to 6. Here’s the corrected code:
clear all
close all
clc
rng("shuffle");
Dice1 = 0;
Dice2 = 1;
s = 0;
while ~(Dice1 == 6 && Dice2 == 6)
Dice1 = Dice2;
Dice2 = randi(6);
s = s + 1;
end
disp(['Number of rolls: ', num2str(s)]);
More Answers (2)
dpb
on 27 Aug 2024
Edited: dpb
on 27 Aug 2024
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.
0 Comments
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?
See Also
Categories
Find more on Simulink Functions 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!