フィルターのクリア

counting rows after fprintf

4 ビュー (過去 30 日間)
yonatan friedman
yonatan friedman 2019 年 12 月 29 日
コメント済み: yonatan friedman 2019 年 12 月 31 日
function printPythagoras(n)
n = 15;
for i = 3:n
for j = 4:n
for k = 5:n
if i^2 + j^2 == k^2 && i<j && n == fix(n)
fprintf('%d^2 + %d^2 = %d^2\n',i,j,k)
end
end
end
end
---------------
after that , i need to write : 'there are 4 combinations' (the number of the rows)
how to do it?
  1 件のコメント
dpb
dpb 2019 年 12 月 29 日
編集済み: dpb 2019 年 12 月 29 日
Add a counter inside the if block, then the appropriate fprintf statement after the all looping is done...

サインインしてコメントする。

回答 (1 件)

Adam Danz
Adam Danz 2019 年 12 月 30 日
As dpb advised, you could use a counter.
n = 15;
counter = 0;
for i = 3:n
for j = 4:n
for k = 5:n
if i^2 + j^2 == k^2 && i<j && n == fix(n)
counter = counter+1;
fprintf('%d^2 + %d^2 = %d^2\n',i,j,k)
end
end
end
end
% Show count
fprintf('There are %d combinations.\n', counter)
Or you could store the outputs in a cell array and display them and the count at the end.
n = 15;
out = {};
for i = 3:n
for j = 4:n
for k = 5:n
if i^2 + j^2 == k^2 && i<j && n == fix(n)
out{end+1,1} = sprintf('%d^2 + %d^2 = %d^2',i,j,k);
end
end
end
end
% Display
disp(strjoin(out,'\n'))
% Show count
fprintf('There are %d combinations.\n', numel(out))
  1 件のコメント
yonatan friedman
yonatan friedman 2019 年 12 月 31 日
thank you

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGeneral Applications についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by