im trying to create a while loop for random numbers and it says if its even or odd

3 ビュー (過去 30 日間)
Kelsey Pettrone
Kelsey Pettrone 2020 年 9 月 9 日
編集済み: James Tursa 2020 年 9 月 9 日
this isnt working for me. The odd counter and the even counter dont add up tp 20. Please help
% Write a program called evens.m that uses a while loop to repeatedly:
% Create a random integer between 1 and 50
% Determine if the integer is even or odd
% Use the rem function, which returns a 0 if x is divisible by y
% For more information, type help rem in the Command Window
% Count the number of integers that are even and number of integers that are odd
% This process should be repeated until 20 even numbers have been generated
% Display the total number of integers generated in the Command Window
clear
clc
%% set parameters
x = randi([1,50])
y = rem(x,2)
Ecounter = 0;
Ocounter = 0;
times = 0;
while times < 20
x = randi([1,50])
if rem(x,2) == 0
Ecounter = 0+1;
end
if rem(x,2) == 1
Ocounter = Ocounter+1;
end
times = times+1;
end
disp(Ocounter)
disp(Ecounter)

回答 (1 件)

James Tursa
James Tursa 2020 年 9 月 9 日
編集済み: James Tursa 2020 年 9 月 9 日
Change this
while times < 20
to this
while Ecounter < 20
and change this
Ecounter = 0+1;
to this
Ecounter = Ecounter+1;
You also need to display the resulting "times" value according to the instructions.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by