使用php计算错误

时间:2013-11-13 07:08:06

标签: php

65 + 10 = 75

75 x 15 x 686 = 771750

771750/365/30 = 70.479 这是正确答案

此代码显示答案错误

这是错误的答案 74.400

我怎么解决它请帮助我 感谢

$res = 65+10*15*686/365/30; //Adding the two values and placing the added result to 'res' variable

<?php //Starting of php 
    if(isset($_POST['submit']))//if the submit button has pressed
    {
    $days = $_POST['days']; //Getting Value of first integer from add.html
    $yeardays1 = $_POST['yeardays1']; //Getting Value of Second integer from add.html
    $yeardays = $_POST['yeardays1']; //Getting Value of Second integer from add.html
    $basicsalary = $_POST['basicsalary']; //Getting Value of Second integer from add.html
    $allowsalary = $_POST['allowsalary']; //Getting Value of Second integer from add.html
    $res = (($basicsalary + $allowsalary)* $days * $yeardays1) / $yeardays /$monthdays;


    echo number_format((round($res, 1)),3);

    }
    //Ending of php
    ?>

4 个答案:

答案 0 :(得分:4)

您的运算符优先级逻辑错误,是时候回到一些基本数学( BODMAS )。但是,根据您的预期优先顺序,您可以使用

<?php
        $res = ((65+10)*15*686)/365/30;
        echo 'Added Result:';

       echo number_format((round($res, 1)),3);

?>
  

添加结果:70.500

Fiddle 基于您的变量

答案 1 :(得分:0)

您刚刚使用了round()函数,因此结果是正确的。在这里阅读php.net/round

更改精度以获得更多数字。

现在我看到有更大的问题。首先评估表达式10*15*686/365/30,然后添加65。所以你提出的结果是不正确的。使用75*15*686/365/30获取结果。

答案 2 :(得分:0)

为什么使用round AND number_format。选择其中一个。

<?php 
    $res = ( 65 + 10 ) * 15 * 686 / 365 / 30; //Adding the two values and placing the added result to 'res' variable
    echo 'Added Result:';

    echo number_format($res,3); /* 70.479 */
    //Ending of php
?>

。+你的算法是假的。

答案 3 :(得分:0)

Php遵循与我们在基础数学BODMAS中学习相同的规则

计算基于运算符的优先级

使用以下代码

<?php
        $res = ((65+10)*15*686)/365/30;
        echo 'Added Result:';

       echo number_format((round($res, 1)),3);

?>