my for loop stop after the first valid number has been found how do i fix this

5 ビュー (過去 30 日間)
Elisa
Elisa 2024 年 8 月 22 日
コメント済み: Elisa 2024 年 8 月 22 日
I am new to Matlab, just learned the for loop, basically the loop run properly, but stop after the first valid number has found.
numbers=importdata('numbers.txt');
result_1=[];
for i =1:numel(numbers);
num=numbers(i);
if mod(num, 10) == 6 && mod(num, 4) == 0
answer_1=[result_1,num];
end
end
fprintf('The numbers that ends in 6 and are divisible by 4: \n');
fprintf('%d\n',answer_1)

採用された回答

Fangjun Jiang
Fangjun Jiang 2024 年 8 月 22 日
Use "result_1", no need to create "answer_1"
numbers=1:100;
result_1=[];
for i =1:numel(numbers);
num=numbers(i);
if mod(num, 10) == 6 && mod(num, 4) == 0
result_1=[result_1,num];
end
end
fprintf('The numbers that ends in 6 and are divisible by 4: \n');
The numbers that ends in 6 and are divisible by 4:
fprintf('%d\n',result_1)
16 36 56 76 96

その他の回答 (0 件)

カテゴリ

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