Function to check if a number is divisible by 5

105 ビュー (過去 30 日間)
hna
hna 2019 年 10 月 13 日
編集済み: Walter Roberson 2023 年 3 月 30 日
How can I write a function m.file that takes as input a real number and checks to see if it is divisible by 5. An appropriate message indicating the result should be the output.
I have tried to write this but it dosen't seem to work as I need the user to input a number and check if it is divisble by 5
function [resp] = div5(x)
if (rem(x,5) == 0)
resp = 1;
else
resp = 0;
end
Thanks in advance
  4 件のコメント
Walter Roberson
Walter Roberson 2019 年 10 月 13 日
No you would use the code from before and then at the command line
div5(10)
Fahrizal Nurcahya
Fahrizal Nurcahya 2020 年 10 月 15 日
編集済み: DGM 2023 年 3 月 30 日
bro it must be like this, check it my function
function [a] = div5(x)
% [x] = div5(x) - to checks a real number if it is divisible by 5.
for a=rem(x,5)
if a~=0
[a] ='NOT divisible by 5.';
else
[a] ='divisible by 5.';
end
end
end

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

回答 (1 件)

AKASH KUMAR
AKASH KUMAR 2023 年 3 月 29 日
編集済み: DGM 2023 年 3 月 30 日
% check "a" is divisible by "b" or not
function test = divisibility_test(a,b)
if ceil(a/b)-a/b==0
test = true;
else
test=false;
end
end
  1 件のコメント
DGM
DGM 2023 年 3 月 30 日
The output of
ceil(a/b)-a/b==0
is a logical array, and the first conditional is only executed if every element of that array is true. So the whole thing simplifies to
function test = divisibility_test(a,b)
test = all(ceil(a/b)-a/b==0);
end
or just
function test = divisibility_test(a,b)
test = all(~mod(a,b));
end

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by