function-loop-if statment

2 次查看(过去 30 天)
Raghad
Raghad 2024-5-21
评论: Dhanesh R 2024-7-8
"Write a function that asks the user to input 10 numbers and calculates the sum of the odd numbers entered (use for loop + if)" I couldn't figure it out at all as functions cannot be added in loops, so im not sure

回答(1 个)

Dhanesh R
Dhanesh R 2024-5-21
I didn't get you correctly. Did you mean this?
function addOnlyOddFromFirstTenNumbers(yourNumberArray)
% Specify your input argument
arguments
yourNumberArray (1, 10) uint64 {mustBeNonnegative, mustBeInteger}
end
% Initialize your output
sumOdds = 0;
% Perform condition based addition
for i = 1:max(10, length(yourNumberArray))
if rem(yourNumberArray(i), 2) ~= 0
sumOdds = sumOdds + yourNumberArray(i);
end
end
% Display your output
fprintf('Sum of odd numbers: %i\n', sumOdds);
end
  2 个评论
Raghad
Raghad 2024-5-21
Thank you! Yes this seems to be the answer, however it does seem a little too complicated for the course level we took, is there no other simplier method to solve this?
Dhanesh R
Dhanesh R 2024-7-8
If you feel the condition placed in the for loop is compliated, you may simply keep it as follows. But then the array must contains 10 elements. If you input less number of elements, MATLAB would throw an error. If you enter more than 10 elements, the function would ignore these extra elements from summing up.
% for i = 1:max(10, length(yourNumberArray))
for i = 1:10
% ...
end
The arguments block can also be ignored if you find it complicated. This block is only to validate the input. You must provide a non-negative integer array.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by