How do I make an if-statement execute only if the value is an integer?

조회 수: 9 (최근 30일)
Hayley Dylla
Hayley Dylla 2014년 11월 5일
답변: Adam 2014년 11월 5일
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에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by