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!