编写自己的函数将十进制数转换为二进制数 [英] Write own function to convert decimal numbers to binary
问题描述
我正在尝试编写自己的函数来将十进制数转换为二进制数.我知道有内置函数,但我正在尝试在这里编写自己的函数,但无法正常工作.
I am trying to write my own function to convert decimal numbers to binary. I know there are build-in functions for this, but I'm trying to write my own here, which I can't get to work correctly.
现在下面的代码没有给我任何输出.我是 PHP 新手,所以提示我哪里出错会有所帮助.
Right now the code below doesn't give me any output. I'm new to PHP so ever hint where I went wrong would help.
代码:
<?php
{
$dec = 0;
if(isset($_POST['num'])) {
$dec = $_POST['num'];
}
decimal_binary($dec);
echo $dec;
}
function decimal_binary($dec)
{
$rem;
$i = 1;
$binary = 0;
while ($dec != 0)
{
$rem = $dec % 2;
$dec /= 2;
$binary += $rem * i;
$i *= 10;
}
$dec = $binary;
echo $binary;
return decimal_binary($dec);
}
?>
<html>
<body>
<form action="3.php" method="POST">
Integer <input type="number" name="num">
<input type="submit">
</form>
</body>
</html>
推荐答案
您刚刚进行了无限递归,我的意思是您正在以结果为参数一遍又一遍地调用该函数.
You just made an infinite recursion, I mean you are calling the function over and over again with the result as parameter.
- 编辑 -
所以你的功能不起作用,但我想出了这个,它确实有效.试试看:
So your function doesn't work, but I came up with this one, and it does work. Try it out:
function decimal_binary($dec){
$binary;
while($dec >= 1){
$rem = $dec % 2;
$dec /= 2;
$binary = $rem.$binary;
}
if($binary == null){
$binary = 0;
}
return $binary;
}
- 结束编辑 -
另外,你需要在调用之前放置函数,调用时需要将它赋值给一个变量,以便你可以在代码的其他部分使用输出值:
Also, you need to place the function before you call it, and when you call it, you need to assign it to a variable so that you can use the output value in other parts of your code:
<?php
// function here
$dec = 0;
if(isset($_POST['num'])){
$dec = $_POST['num'];
}
$bin = decimal_binary($dec);
?>
这篇关于编写自己的函数将十进制数转换为二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!