首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >变量间算术运算

变量间算术运算
EN

Stack Overflow用户
提问于 2014-12-05 16:30:40
回答 2查看 2.2K关注 0票数 4

我是php的初学者。我试图在两个变量之间应用一些随机算术运算。

代码语言:javascript
运行
复制
$operators = array(
    "+",
    "-",
    "*",
    "/"
    );

$num1 = 10;
$num2 = 5;

$result = $num1 . $operators[array_rand($operators)] . $num2;

echo $result;

它打印如下的值

代码语言:javascript
运行
复制
10+5
10-5

如何编辑我的代码才能完成这个算术操作?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-05 16:35:08

虽然您可以使用eval()进行此操作,但它依赖于安全的变量。

这要安全得多:

代码语言:javascript
运行
复制
function compute($num1, $operator, $num2) {
    switch($operator) {
        case "+": return $num1 + $num2;
        case "-": return $num1 - $num2;
        case "*": return $num1 * $num2;
        case "/": return $num1 / $num2;

        // you can define more operators here, and they don't
        // have to keep to PHP syntax. For instance:
        case "^": return pow($num1, $num2);

        // and handle errors:
        default: throw new UnexpectedValueException("Invalid operator");
    }
}

现在你可以打电话:

代码语言:javascript
运行
复制
echo compute($num1, $operators[array_rand($operators)], $num2);
票数 6
EN

Stack Overflow用户

发布于 2014-12-05 16:32:39

这应该对你有用!

您可以使用此函数:

代码语言:javascript
运行
复制
function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = preg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators

    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
}

//As an example
echo calculate_string("10+5");

输出:

代码语言:javascript
运行
复制
15

所以在你的情况下,你可以这样做:

代码语言:javascript
运行
复制
$operators = array(
    "+",
    "-",
    "*",
    "/"
    );

$num1 = 10;
$num2 = 5;

echo calculate_string($num1 . $operators[array_rand($operators)] . $num2);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27320473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档