MatLab Cody Course Work Help Please

48 views (last 30 days)
Alyssa Davenport
Alyssa Davenport on 15 Mar 2017
Edited: Brandon J. DeHart on 31 May 2017
I'm working on a problem for a concept learned yesterday in class. The question is seen below.
A zombie picks up a calculator and starts adding odd whole numbers together, in order: 1 + 3 + 5......etc. What will be the last number added that will make the sum on his calculator greater than 10,000?
Write the MATLAB code necessary to solve this problem for the zombie or he will eat your brain. Create a function with an input of the target number (in the scenario given above the target number would be 10,000), which outputs the last numbered added.
% Write your problem statement here
% Input variable:
% maxTotal - the target value which is input into the function
% Output variable:
% lastNum - the last number added to the sume to make the total be greater than the maxTotal value
%%Inputs - Uncomment variables in this section to test in Matlab, but leave commented out when testing in Cody
% maxTotal = 10000;
% Write your entire function code below here (Including header)
function [lastNum] = zomSum(maxTotal)
sum=1
lastNum=1
while sum<maxTotal
sum = sum+2
lastNum=lastNum+2
end
fprintf('The last number is %0.0f.\n', lastNum)
end
The error message just says that the last number added is incorrect. I'm not quite sure what I'm doing wrong. Any help is greatly appreciated.
Thank You!

Answers (2)

Walter Roberson
Walter Roberson on 15 Mar 2017
Your code will always have sum and lastNum equal. The required output is the last number before it goes over.

Brandon J. DeHart
Brandon J. DeHart on 31 May 2017
Edited: Brandon J. DeHart on 31 May 2017
Your code is just adding 2 to the sum and 2 to the last number at each iteration, which is not what the question has asked for.
You need to keep track of two different things: the sum of the odd numbers, and whatever odd number you added last. As the code is right now, sum and lastNum will always be equal and will result in lastNum = sum = maxTotal + 1 (for an even maxTotal).

Categories

Find more on Simulink in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!