серия суммирования с использованием октавы цикла while

Суммирование

sun=0;
i=0;
while(i<=20)
while(j<=5)
y=i+2j
j=j+1;
end
j=0;
i=i+1
end

Не удалось с ошибкой

когда я запускаю его, он отображает много y=20+i

1 ответ

Решение

С этим кодом много проблем.
Вот очищенная версия ниже (т.е. соответствующий отступ, интервал и т. Д.) С комментариями

sun = 0;   % What's the `sun` doing here? Did you mean `y`?
i   = 0;
           % Where's the initialisation of j in this list?
           %    You are using it below uninitialised!

while i <= 20   % Octave/matlab does not need brackets in `while`, `for`,
                %   `if` statements, etc.

    while j <= 5        % Proper indentation clarifies scope of 
                        %   outer 'while' block

        y = i + 2 * j   % Octave/matlab do not support '2j' syntax.
                        %   You need to multiply explicitly.

        j = j + 1;

    end

    j = 0;      % Why aren't you resetting this *before* the inner loop? 
                % How do you think your sum will be affected if `j` is,
                %   let's say `10`, at the start of this program?

    i = i + 1   % Are you leaving the `;` out intentionally here?
                %   (and `y` above?). If you don't want these values
                %   printed on the console each time, put a `;` at the end.
end
Другие вопросы по тегам