PHP命令行字符串添加

时间:2018-09-02 09:25:40

标签: php sum command-line-interface

为什么在命令行中输入的结果总和为零,而在程序内部进行加法却得出结果。我的代码如下:

echo "Enter the first number: ";
$num1 = trim(fgets(STDIN));
// echo $num1;
echo "Enter the second number: ";
$num2 = trim(fgets(STDIN));
// echo $num2;
$z= $num1 + $num2;  

$a = "2";
$b = "2";

echo "Sum of the numbers: ".$z." - ".($a+$b); 

如果我为端子上的两个数字都提供输入“ 2”,则结果为零。结果看起来像数字总和:0-4 ,为什么?

2 个答案:

答案 0 :(得分:1)

我确实复制了粘贴,似乎可以正常工作。
但是我想我知道您的问题,您输入的是“ 2”-双引号吗?
当我输入“ 2”时,结果与您相同。
现在,当您在输入中输入“ 2”时,您实际上在代码中会得到“ \” 2 \”,这当然不是数字,因此将其修整可能是您的解决方案:

echo "Enter the first number: ";
$num1 = trim(fgets(STDIN), '"');
// echo $num1;
echo "Enter the second number: ";
$num2 = trim(fgets(STDIN), '"');
// echo $num2;
$z= $num1 + $num2;

$a = "2";
$b = "2";

echo "Sum of the numbers: ".$z." - ".($a+$b);

答案 1 :(得分:0)

我认为这是一个版本问题。对我来说效果很好。.我正在使用php 7.1

enter image description here

无论如何,尝试

<?php
echo "Enter the first number: ";
$num1 = trim(fgets(STDIN));
// echo $num1;
echo "Enter the second number: ";
$num2 = trim(fgets(STDIN));
// echo $num2;
$z= (int) $num1 + (int) $num2;  

$a = 2;
$b = 2;

echo "Sum of the numbers: ".$z." - ".($a+$b); 
?>