Finding decimal values without mod

2 ビュー (過去 30 日間)
Jose Grimaldo
Jose Grimaldo 2020 年 4 月 2 日
回答済み: Ameer Hamza 2020 年 4 月 2 日
Is it possible or is there any way to find a value in an array that is a decimal without using mod(or any other function)?
  5 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2020 年 4 月 2 日
編集済み: KALYAN ACHARJYA 2020 年 4 月 2 日
"For example, i want to separate the odd and even integers. I know there is easier ways,but i cant use functions only loops. (its a hw problem)"
You asked for with loop and without mod function, you can do multiple ways-
A=[1; 2; 3; 4; 5; 6; 7; 8]
m=1;n=1;
for i=1:length(A)
if rem(A(i),2)==0
EvenV(m)=A(i); % I want to store the Even integers
m=m+1;
else
OddV(n)=A(i); % i want to store the odd integers
n=n+1;
end
end
EvenV
OddV
James Tursa
James Tursa 2020 年 4 月 2 日
You are going to have to use some functions for this. Even the / you are currently using is a function. Which functions are explicitly forbidden?

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

回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 4 月 2 日
Right now, this is the only way I can think of to detect even and odd numbers without using any rounding functions and just a while loop. I suspect there might be more efficient solutions.
A=[1; 2; 3; 4; 5; 6; 7; 8];
Evens = [];
Odds = [];
for i=1:numel(A)
x = A(i);
tf = isEven(x);
if tf
Evens = [Evens x];
else
Odds = [Odds x];
end
end
function tf = isEven(x)
x = abs(x);
while true
x = x - 2;
if x == 0
tf = 1;
return
elseif x < 1
tf = 0;
return
end
end
end

カテゴリ

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