【发布时间】:2020-11-19 08:31:31
【问题描述】:
我正在尝试开发一个打破数学规则的简单计算器。我希望它忽略通常的数学规则并从右到左执行。用户输入整个字符串作为数学问题。 例如:
输入:123 - 10 + 4 * 10
应该这样解决:
123 - 10 + 4 * 10 = 123 - ( 10 + ( 4 * 10 ) ) = 73。
这是我目前拥有的:
use strict;
use warnings;
use feature 'say';
while (<>) { # while we get input
my ($main, @ops) = reverse /[\d+\-*\/]+/g; # extract the ops
while (@ops) { # while the list is not empty
$main = calc($main, splice @ops, 0, 2); # take 2 items off the list and process
}
say $main; # print result
}
sub calc {
my %proc = (
"+" => sub { $_[0] + $_[1] },
"-" => sub { $_[0] - $_[1] },
"/" => sub { $_[0] / $_[1] },
"*" => sub { $_[0] * $_[1] }
);
return $proc{$_[1]}($_[0], $_[2]);
}
这是我得到的输出: 123 - 10 + 4 * 10 = ((123 - 10) + 4) * 10 = 1170
如您所见 - 它从左到右解决了问题。我的问题是 - 我怎样才能扭转这种局面?我希望它从右到左解决。任何帮助将不胜感激,谢谢。
【问题讨论】:
-
实际上,您的代码确实会根据您提供的输入返回 -73
-
您的问题是基于错误的前提。计算是从右到左进行的,但操作也是相反的。当你应该得到
73时,你得到了-73。我在回答中解决了这个问题
标签: function perl math calculator