While loop problems finding lowesst value
16 次查看(过去 30 天)
显示 更早的评论
Im writing a code to find the lowest value of x which is dividable by 11 and bigger than sqrt(132), x is also a odd number. I dont understand whats wrong with my code under. Any help is appreciated.
odd = rem(x, 2) ~= 0
while x > sqrt(132)
if x / 11
min x
else
fprintf('Try again/n')
end
end
1 个评论
S. Walter
2020-10-27
Your if statement is incomplete - right now it just says: "If the array of x is divided by 11, give the minimum value of x". It doesn't even get to the else part.
You want your if statement to say something like "If x divided by 11 has no remainder, give me that value of that x", then check to make sure it's odd and bigger than sqrt(132).
回答(1 个)
Adam Danz
2020-10-27
编辑:Adam Danz
2020-10-27
"I dont understand whats wrong with my code"
Let's go line-by-line.
odd = rem(x, 2) ~= 0
Odd numbers are whole numbers. rem(2.1, 2) equals 0.1 which is not equal to 0 and would be misclassified as odd. I guess that you want to force the user to provide an integer for x in which case you could throw an error if x is not an integer
assert(mod(x,1)==0, 'x must be an integer.')
or you could add an integer test to the condition,
odd = rem(x,2)~=0 & mod(x,1)==0;
while x > sqrt(132) ... end
- What happens when x is less than sqrt(132)?
- Your while-loop never changes the value of x so the while-loop will be infinite.
if x / 11
Is x scalar? Unless x=0, this condition will always be true. If-statements should contain a binary condition that tests for true or false. Any scalar other than 0 will satisfy this condition. If x is a vector or array the if-statement is even more problematic and should be replaced by indexing. If you want to test whether x is divisible by 11, use
mod(x,11)==0
min x
" Im writing a code to find the lowest value of x which is dividable by 11 and bigger than sqrt(132), x is also a odd number."
x = 1:1000;
idx0 = mod(x,1)==0; % is integer
idx1 = mod(x,11)==0; % divisible by 11
idx2 = x < sqrt(132); % less than sqrt 132
idx3 = mod(1:10,2)==1 % is odd
Now combine those indices to pull out values of x that satisfy all tests and apply min().
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!