Using the floor function to separate numbers
Show older comments
I am working on an assignment where I have to list all the numbers from 1-200 whose individual sum is odd (e.g 12 = 1 + 2 = 3 and therefore odd, and shall therefore be placed into an array. I have written the code where I am only testing the numbers from 10:18 just to make sure the concept works on a small scale. The problem I am having is removing the number 11 from my output array. With the code I have written, it does not make sense to me why the 11 still remains. Please can someone assist.
a = 0;
for k = 10:18;
a = a + 1;
initial = k / 10;
initial2 = floor(initial);
secondary = (initial - initial2)*10;
outcome = secondary + initial2;
if mod(outcome,2) ~=0
arrayinitialodd(a) = [k]
end
end
///////////////////////////////
output:
arrayinitialodd =
10 11 12 0 14 0 16 0 18
///////////////////////////////////////
Proof of operation I get in the command window with respect to the number 11:
a = 2
initial = 1.1000
initial2 = 1
secondary = 1.0000
outcome = 2.0000
value = 11
arrayinitialodd =
10 11
Accepted Answer
More Answers (1)
Star Strider
on 21 Apr 2016
You’re experiencing floating-point approximation error. You can see that if you change to format long E and remove the semicolon from your ‘outcome’ assignment.
Solution: use mod or rem for secondary instead:
secondary = rem(k,10);
Also, put the ‘a’ increment inside the if block.
1 Comment
dillon-harris
on 21 Apr 2016
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!