While cycle with conditions never ending
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Piyush Kumar
2024-8-27
@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)]);
更多回答(2 个)
dpb
2024-8-27
编辑:dpb
2024-8-27
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 个评论
Steven Lord
2024-8-27
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?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulink Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!