フィルターのクリア

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

2 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by