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!

回答(2 个)

Geoff Hayes
Geoff Hayes 2014-11-5
编辑:Geoff Hayes 2014-11-5
Hayley - you could try using the floor or ceil functions. For example, if we assume that c is a number (so not NaN or Inf) then
c<=50 && c==floor(c)
would be a sufficient condition for your if statement.

Adam
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by