function-loop-if statment
1 次查看(过去 30 天)
显示 更早的评论
"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
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!