How do I make an if-statement execute only if the value is an integer?
1 次查看(过去 30 天)
显示 更早的评论
This is the question: The pythagorean theorem states that a^2+b^2=c^2. Write a MATLAB program that finds all the combinations of triples a, b, and that are positive integers all smaller or equal to 50 that satisfy the Pythagorean theorem. Display the results in a three-column table in which every row corresponds to one triple. The first three rows of the table are:
3 4 5
5 12 13
6 8 10
What I've come up with is:
for a=1:1:50
for b=1:1:50
c=sqrt(a^2+b^2);
if (c<=50)
??????????????????????
fprintf('%3i %3i %3i\n', a, b, c)
end
b=b+1;
end
end
I know something needs to go where the question marks are in order to determine whether c is an integer...I just don't know what!
0 个评论
回答(2 个)
Adam
2014-11-5
I have a utility function for this since it is something I have needed on a couple of occasions:
function valIsInt = isIntegerValued( val )
validateattributes( val, { 'single', 'double' }, { 'nonempty' } )
tolerance = 1e-10;
if isa( val, 'single' )
tolerance = 1e-5;
end
valIsInt = ( abs( round( val ) - val ) ) <= tolerance;
end
Obviously you can set tolerance to whatever you want, but that works for my purposes.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!