Error in coin toss code

12 次查看(过去 30 天)
Chaim Feigen
Chaim Feigen 2019-12-25
Trying to write a program to run a set number of trials where I flip n coins (chosen by user) successively and display the number of heads. I get this error when I run it
Error: File: coins.m Line: 5 Column: 1
At least one END is missing: the statement may begin here.
Here is the source code:
trial = 0;
C= 0;
head=0;
coins=input('How many coins to flip?');
while trial<10
while C<coins
rando=rand;
if rando>0.5
head=1+head;
else
head = 0+head;
C=C+1;
print(head)
end
trial = trial+1
end

回答(1 个)

Image Analyst
Image Analyst 2019-12-25
If you type control-a (to select all) then control-i (to properly fix indenting) you'll see that an end is indeed missing:
trial = 0;
C= 0;
head=0;
coins=input('How many coins to flip?');
while trial<10
while C<coins
rando=rand;
if rando>0.5
head=1+head;
else
head = 0+head;
C=C+1;
print(head)
end
trial = trial+1
end
This works and is based on your code, though there are better ways to do it, such as replacing the while with a for and getting a vector of all coin tosses in advance using randi() instead of using rand().
trial = 0;
C = 0;
head = 0;
coins = input('How many coins to flip? ');
maxTrials = 10;
while trial < maxTrials
fprintf('Now beginning experiment number %d ...\n', trial)
for k = 1 : coins
rando = rand;
if rando > 0.5
head = 1 + head;
fprintf(' Coin %d is a head.\n', k)
else
fprintf(' Coin %d is a tail.\n', k)
end
end
trial = trial+1;
end
fprintf('Flipped %d heads (%.2f%%) over all %d experiments and %d total tosses.\n', ...
head, 100 * head / (maxTrials*coins), maxTrials, maxTrials*coins);

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by