【发布时间】:2013-10-30 00:05:28
【问题描述】:
我是 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);
【问题讨论】:
-
旁注:您的问题陈述需要至少与螺栓一样多的螺母,但您正在测试是否相等。
-
感谢您提供清晰的问题陈述。这种情况发生的频率还不够!
标签: matlab if-statement