I'm new to MATLAB (but not new to programming) and in my engineering class they are simply teaching the basics of if/elseif/else and loops. Well we have a homework assignment and I feel ashamed that I cannot figure it out. I must be missing the simplicity in it somewhere.
Write a program that ask the user for the number of bolts, nuts, and washers in their purchase and the calculates and prints on the total. That's fine, and I've completed this part.
Here is where it gets a little confusing...
As an added feature, the program checks the order. A correct order must have at least as many nuts as bolts and at least twice as many washers as bolts, otherwise the order has an error. These are the only 2 errors the program checks: too few nuts and too few washers. For an error the program prints "Check the order: too few nuts" or "Check the order: too few washers" as appropriate. Both error messages are printed if the order has both errors. If there are no errors the program prints "Order is OK." CONFUSING PART ---> You can accomplish this with only one set of if -elseif- else statements.
How can I make this program print both with one if-elseif-else statement if both are true?
Here is my code:
% Get the amount each part
bolts = input('Enter the number of bolts: ');
nuts = input('Enter the number of nuts: ');
washers = input('Enter the number of washers: ');
% Check for the correct amount of nuts, bolts, and washers
if bolts ~= nuts
disp('Check order: too few nuts');
elseif bolts * 2 ~= washers
disp('Check order: too few washers');
else
disp('Order is OK.');
end
% Calculate the cost of each of the parts
costOfBolts = bolts * .05;
costOfNuts = nuts * .03;
costOfWashers = washers * .01;
% Calculate the total cost of all parts
totalCost = costOfBolts + costOfNuts + costOfWashers;
% Print the total cost of all the parts
fprintf('Total cost: %.2f\n', totalCost);
A hint for you to think about: a "set of if-elseif-else" statements can have multiple elseif's.
This seems like a slightly clumsy approach, but if you must do it in a single if-elseif-else statement, this is one way to achieve it:
% Check for the correct amount of nuts, bolts, and washers
if (nuts < bolts) && (washers < 2*bolts)
disp('Check order: too few washers');
disp('Check order: too few nuts');
elseif washers < 2*bolts
disp('Check order: too few washers');
elseif nuts < bolts
disp('Check order: too few nuts');
else
disp('Order is OK.');
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With