我是 MATLAB 新手(但对编程并不陌生),在我的工程课上,他们只是在教授 if/elseif/else 和循环的基础知识。好吧,我们有一个家庭作业,我为自己无法弄清楚而感到羞愧。我一定在某处错过了它的简单性。
编写一个程序,询问用户购买的螺栓、螺母和垫圈的数量,并计算和打印总数。没关系,我已经完成了这部分。
这是它变得有点混乱的地方......
作为一项附加功能,该程序会检查订单。一个正确的订单必须有至少和螺栓一样多的螺母和至少两倍于螺栓的垫圈,否则订单就有错误。这些是程序检查的仅有的 2 个错误:螺母太少和垫圈太少。对于错误,程序会酌情打印“检查顺序:螺母太少”或“检查顺序:垫圈太少”。如果订单有两个错误,则会打印两个错误消息。如果没有错误,程序会打印“Order is OK”。令人困惑的部分 ---> 您只需使用一组if -elseif- else语句即可完成此操作。
如果两者都为真,我如何让这个程序用一个 if-elseif-else 语句打印两者?
这是我的代码:
% 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);