【问题标题】:if-elseif-else statement help for MATLABMATLAB 的 if-elseif-else 语句帮助
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 我把声明误解为只有一个elseif
【解决方案2】:

这似乎是一种有点笨拙的方法,但如果您必须在单个 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

【讨论】:

  • 是的,我也想过这样做,但不喜欢复制代码的想法哈哈。谢谢!
  • @inquisitor 你能在一个 if-elseif 语句中解决这个问题,而无需复制代码吗?
  • 不,先生,我是按照您在这里的方式进行的。我不知道其他方法。
【解决方案3】:

您有很多选择来解决上述问题。 您可以在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2018-08-02
    相关资源
    最近更新 更多