PHP命令行字符串添加

问题描述 投票:0回答: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); 

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

php sum command-line-interface
2个回答
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);

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); 
?>
© www.soinside.com 2019 - 2024. All rights reserved.