Using the floor function to separate numbers
显示 更早的评论
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
采纳的回答
更多回答(1 个)
Star Strider
2016-4-21
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!