2

我是 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);
4

3 回答 3

7

提示您考虑:“一组if-elseif-else ”语句可以有多个elseif

于 2013-10-30T00:17:27.247 回答
4

这似乎是一种有点笨拙的方法,但如果您必须在单个 if-elseif-else 语句中执行此操作,这是实现它的一种方法:

% 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
于 2013-10-30T00:18:35.060 回答
0

你有很多选择来解决上述问题。您可以在 if 中使用 if 来检查条件,或者如@nispio 所述,您可以编写程序。正如@nispio 已经说明的解决方案之一,我将说明另一个解决方案。可能这不是一个合适的答案,因为我使用了多个 if else 语句!

bolts = input('Enter the number of bolts: ');
nuts = input('Enter the number of nuts: ');
washers = input('Enter the number of washers: ');

if bolts > nuts
    fprintf('Check order: Too few nuts\n');
    if 2*washers < bolts
        fprintf('Check order: Too few washers\n');
    end
elseif 2*washers < bolts
    fprintf('Check order: Too few washers\n');
else
    fprintf('Order is OK.');
end
于 2016-01-07T16:22:37.950 回答