Finding all numbers which is divisible by 5

76 ビュー (過去 30 日間)
Takashi Fukushima
Takashi Fukushima 2019 年 11 月 6 日
コメント済み: Takashi Fukushima 2019 年 11 月 6 日
Hello,
I would like to write a program which identifies all number which divisible by 5 by using while loop and mod.
Here is what I have so far.
a=input('Enter the threshold: ');
disp('Following number is devided by 5' + a);
number = 1;
while number<=a
if mod(a,5)==0
disp(a);
end
number=number+1
end
disp("The following numbers are divisible by 5: " + mod)
and the outcome display should look like this...
Enter the threshold: 100(For example)
The following numbers are divisible by 5: 5, 10, 15, 20 ...100(For example of threshold 100)
I really appreciate your response in advance!
  2 件のコメント
Geoff Hayes
Geoff Hayes 2019 年 11 月 6 日
Takashi - one problem with the code is that on each iteration of the while loop, you are always using a with
if mod(a,5)==0
disp(a);
end
Since a never changes, then I suspect that you want to be using number instead.
Do you need to use a while loop? Is this a condition of the assignment/homework?
Also, consider using fprint (instead of disp) to write out your messages and the numbers that are divisible by 5.
Takashi Fukushima
Takashi Fukushima 2019 年 11 月 6 日
Yes I have to use while loop since it's homework.
I was wondering using number instead of a. Thanks for your info!

サインインしてコメントする。

採用された回答

Jeremy
Jeremy 2019 年 11 月 6 日
編集済み: Jeremy 2019 年 11 月 6 日
Hi,
In your mod command you want to compare the number variable to 5, not a (a doesn't change). This is why you're getting unexpected results. I would use zeroes to initialize z so that you can save each number that is divisible by 5 like:
a=input('Enter the threshold: ');
number = 1; z = zeros(1,a);
while number <= a
if mod(number,5) == 0
z(number) = number;
end
number=number+1;
end
And then use
find
to extract the indices of z that are nonzero and print them out.
I hope this helped

その他の回答 (1 件)

Turlough Hughes
Turlough Hughes 2019 年 11 月 6 日
This is your answer assuming the while loop is a must:
a=input('Enter the threshold: ');
disp("Following number is devided by 5: " + a);
number = 1;
count=1;
output=[];
while number<=a
if mod(number,5)==0
disp(number);
output(count)=number;
count=count+1;
end
number=number+1;
end
disp(['The following numbers are divisible by 5: ' num2str(output)])
Though you could do it also without a loop:
a=input('Enter the threshold: ');
disp("Following number is devided by 5: " + a);
range=1:a;
output=range(mod(range,5)==0)
disp(['The following numbers are divisible by 5: ' num2str(output)])

カテゴリ

Help Center および File ExchangeSubplots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by