Why my code doesn't detect appropriate natural numbers?
显示 更早的评论
Welcome!
I try to create a program. I decided to cut an algorithm responsible for detecting natural numbers to exhibit my problem.
a = input('Enter a number: '):
if(a>0 && mod(a,1)==0)
disp('Good!');
else
disp('No!');
end
However, when value of a has more than 15 digits, ex. 1.00000000000000000001, my program responds to the request against the expectations ('Yes!' instead of 'No!'). Apparently, code lacks one line (after input, before condition) to function properly. What line is missing?
回答(2 个)
Azzi Abdelmalek
2013-1-11
编辑:Azzi Abdelmalek
2013-1-11
1.00000000000000000001==1
the result is 1
The precision has a limit
4 个评论
Azzi Abdelmalek
2013-1-11
try this
a = input('Enter a number: ','s')
if ~isequal(a(1),'-') && any(ismember(a,'.'))==0
disp('Good!');
else
disp('No!');
end
Patryk Ulatowski
2013-1-11
Azzi Abdelmalek
2013-1-11
I gave just a hint, you can make more analyze.
Walter Roberson
2013-1-11
If it is for compatibility with other modules then you are receiving the value numerically and so cannot receive a 1.00000000000000000001 because that cannot be passed through.
If your code is the one that is going to be reading the input from the user, then validate it first as a string and the convert the string to numeric to be passed on.
a = input('Enter a number: ','s')
if regexp(a, '^\d+(\.0*)')
disp('Good!')
a = str2num(a);
else
disp('No!')
end
Walter Roberson
2013-1-11
1.00000000000000000001 and 1 are represented the same way in MATLAB.
Note that when you use input() and do not use the 's' option, anything typed in is evaluated before being returned, so of the user were to enter something like
exp(3)/pi
as the input, that would be evaluated numerically and the result returned from input(). If you do not want that, use the 's' option of input() so that the input is a string; then analyze the string.
类别
在 帮助中心 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!