Error in coin toss code
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (1)
Image Analyst
le 25 Déc 2019
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);
0 commentaires
Voir également
Catégories
En savoir plus sur Entering Commands dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!