フィルターのクリア

Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Can someone check it for me ?

1 回表示 (過去 30 日間)
bob  shot
bob shot 2012 年 12 月 12 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Write a program to find the first odd integer whose cube is greater than an integer entered by the user.
This is how far I got but it's working for some numbers however for some it's not
Can you check or tell me what did I do wrong ?
%MATLAB Programming Problem 22
int = input('Please input an integer: ');
%If the integer input integer is even, add 1
cube = int.^(1/3);
if cube > int^(1/3);
cube = cube + 0;
else
cube = cube + 2;
end
if rem(cube, 2) == 0
cube = cube + 1;
else
cube = cube + 0;
end
fprintf('The first odd integer is %1.0f\n', cube)

回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 12 月 12 日
You define
cube = int.^(1/3)
and then in the next line compare
cube > int^(1/3)
so you are logically comparing
int^(1/3) > int^(1/3)
and logically speaking that is going to always be false. A test that is always false is seldom worth coding.
I did say "logically speaking" though. Real computations with floating point numbers are such that if you calculate an expression in two different but algebraically identical ways, the results are not necessarily going to be exactly the same. But which one would come out higher or lower is quite tricky to predict. It is possible in real computer languages for the test you created to turn out true, and you would have a difficult time figuring out the circumstances in advance.
So, whatever it is you think you are testing there, you'd better test it more robustly.
  1 件のコメント
Greg Heath
Greg Heath 2012 年 12 月 13 日
help int
help ceil
Hope this helps
Greg

この質問は閉じられています。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by