虽然已经满足了creteria,但循环仍在继续

时间:2018-04-06 14:55:44

标签: matlab fibonacci

你好我需要这个计数一旦我的变量' fourMil'是< = o但循环继续,IDK为什么。一些帮助将不胜感激。

% Sum of the Fibonacci pair numbers until 4 million

 clc
    clear

    fibo_list = [];
    for i = (0:31)
        if (i == 0 ||  i == 1 || i == 2)
            fibo_list(end+1) = i + 1;
        else
            fibo_list(end+1) = fibo_list(end) + fibo_list(end-1);
        end
    end

    filtered_list = [];
    fourMil = 4000000;

    while fourMil > 0
        for i = fibo_list     
            if mod(i,2) == 0
                filtered_list(end+1) = i;
                fourMil = fourMil - filtered_list(end);


            end
        end    
    end
    sumation = sum(filtered_list);
    fprintf('the sum of the Fibo numbers is %i\n', sumation)

1 个答案:

答案 0 :(得分:0)

当满足条件时,您可以使用break语句来中断while循环:

while fourMil > 0

    for i = fibo_list 

        if mod(i,2) == 0
            filtered_list(end+1) = i; 

            if (fourMil - filtered_list(end)<0) 
                break; %This will break the loop
            end

            fourMil = fourMil - filtered_list(end)
        end
    end    
end