PHP - 仅当余数为 0 时才执行(和回显)操作 - 进入无限循环

发布于 2024-10-07 19:43:13 字数 1768 浏览 3 评论 0原文

让我从结尾和实际问题开始:

我正在尝试编写一个 PHP 脚本,只有我们输出并解析两个随机数 $x$y当 modulo == 0 (它应该始终回显有效函数)

我的意思是:

脚本回显:

4 / 2 =>好的!

脚本回显:

4 / 3 =>坏的!

什么都没有=>坏的!


我会尽力引导您完成我的推理,但请注意:

我是新手,所以:我学到了一些东西,提高了赌注,并尝试方便地应用它。


首先我生成随机数,简单:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

现在我说,除法后有两种可能性,余数为 0 或不为 0,因此 if() 语句看起来是个好主意,所以我这样做:

if($x % $y == 0){

echo $x 。 “/”。 $y;

}else{

echo "余数不为0";

这按预期工作,当然,我总是想生成这个余数不是 0 除法

所以我的方法如下,为什么不使用用户生成的函数(以前从未使用过但可以派上用场)所以,如果我知道这个 工作得很好

<?php
 
function hello(){   
      echo "Hello!";  
}
 
hello();
?>

为什么不像我之前所说的那样提高赌注并使用它,所以我混合了:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);
 
function foo(){
 
if($x % $y == 0){
 
echo $x . "/" . $y;
 
}else{
        
foo();  
        
}
 
}
 
?>

它不起作用,我得到一个空白屏幕。

我对这个脚本的期望是什么:

  • 创建一个带有 if() 语句的函数
  • 如果余数为 0,很好,回声。
  • 否则,从头开始,一次又一次,直到得到一个没有余数的除法。

这是行不通的。

所以我基本上会问,我做错了什么?这后面的线有什么问题吗?

这可以通过微妙的改变起作用吗?


对于经验丰富的编码人员,我知道你们都可以使用 MS PAINT 作为 IDE 制作一个脚本来执行此操作(但与我的无关),但是:

我对代码本身不感兴趣,因为这仅用于学习目的。

这不是我第一次遇到这种情况,我经常因为无限循环而碰壁,所以变化越小(解释越大)越好,并且将非常感激。

提前致谢!


现在完成后,我刚刚意识到问题甚至可能不是无限循环,即使问题不再存在,您对我的方法有何看法? (当然我也会编辑并删除问题中的无限循环)

Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!


I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.


First I generate the random numbers, easy:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

<?php
 
function hello(){   
      echo "Hello!";  
}
 
hello();
?>

Why not up the ante as I said before and use it, so I mix the up:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);
 
function foo(){
 
if($x % $y == 0){
 
echo $x . "/" . $y;
 
}else{
        
foo();  
        
}
 
}
 
?>

It doesn't work, I get a blank screen.

What was I expecting from this script:

  • Create a function with an if() statement on it
  • If the remainder is 0, great, echo.
  • else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?


To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!


Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

月寒剑心 2024-10-14 19:43:13

在我看来,您只设置了 $x$y 一次

这意味着当您递归调用 foo() 时它们不会改变。我首先尝试这样的事情:

<?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        if ($x % $y == 0) {
            echo $x . "/" . $y;
        } else {
            $x = mt_rand(1,10);    # need to recalculate them here.
            $y = mt_rand(1,10);
            foo();  
        }
    }
?>

不过我会检查该代码。我了解 PHP 和了解阿拉姆语 :-) 我的分析更多地基于一般语言知识,因此语法可能是假的。

当然,在这种情况下,您可能需要考虑完全避免递归。确实没有必要。当递归使您的代码更加优雅时,它就很好,但我不认为这里是这种情况。我会尝试这样的事情:

<?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        while ($x % $y != 0) {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        echo $x . "/" . $y;
    }
?>

It looks to me like you only set $x and $y once.

That means they won't change when you recursively call foo(). I'd start by trying something like this:

<?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        if ($x % $y == 0) {
            echo $x . "/" . $y;
        } else {
            $x = mt_rand(1,10);    # need to recalculate them here.
            $y = mt_rand(1,10);
            foo();  
        }
    }
?>

I'd check that code though. I know PHP about as well as I know Aramaic :-) My analysis is based more on general language knowledge, so the syntax may be bogus.

Of course, you may want to think about avoiding recursion altogether in this case. There's really no need for it. Recursion is fine when it makes your code more elegant but I don't believe that's the case here. I'd give something like this a shot:

<?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        while ($x % $y != 0) {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        echo $x . "/" . $y;
    }
?>
任谁 2024-10-14 19:43:13

好吧,让我们从基础开始。

您的应用程序不显示任何内容的原因是您没有告诉它。您已经定义了一个将显示某些内容的函数,但您从未真正调用过它。

基本上,您需要执行以下操作:

function foo() {
  // foo logic
}


foo();

注意如何在应用程序的主线逻辑中在函数本身之外对 foo 进行调用。

接下来,您需要将对 mt_rand() 的调用移至 foo() 函数内部,以便生成新的随机数每次通话时。

最后,您不需要从foo()内部调用foo()。这样做是允许的,并且称为“递归”,但这里确实不需要。您应该做的是设置您的函数,以便在函数完成时返回一个布尔值(即 true/false),让您知道它有效。然后,您可以设置一个 while 循环来重复执行该函数,直到它正确完成。

这是一个例子:

function foo() {
  //define the random values
  $x = mt_rand(1,10);
  $y = mt_rand(1,10);

  //if they match, echo the statement and return true so the loop ends
  //otherwise, return false so the loop repeats
  if (($x % $y) == 0) {
    echo $x . "/" . $y;
    return true;
  } else {
    return false;
  }
}

//we're now *outside* of the function, and in mainline logic

//setup a variable to hold the return value of the function
//initialize it to false so that the first loop executes
$foundEquation = false;


//execute the function in a loop until we find
//the right equation
while(!$foundEquation) { 
  $foundEquation = foo();
}

这能回答你的问题吗?如果您在理解这里发生的事情时遇到任何困难,请告诉我。我很高兴澄清有关此代码的任何内容。

Alright, let's start with the basics.

The reason why your application isn't displaying anything is because you haven't told it to. You've defined a function which will display something, but you've never actually called it.

Basically, you need to do this:

function foo() {
  // foo logic
}


foo();

Notice how the call to foo is made outside of the function itself, in the mainline logic of the application.

Next, you need to move your calls to mt_rand() to be inside your foo() function, so that new random numbers will be generated on every call.

Finally, you don't need to make calls to foo() from within foo(). Doing this is allowed, and is something called "recursion", but it's really not needed here. What you should do is set your function up so that it returns a boolean (i.e. true/false) value when the function finishes, letting you know that it worked. You can then setup a while loop to repeatedly execute the function until it completes properly.

Here is an example:

function foo() {
  //define the random values
  $x = mt_rand(1,10);
  $y = mt_rand(1,10);

  //if they match, echo the statement and return true so the loop ends
  //otherwise, return false so the loop repeats
  if (($x % $y) == 0) {
    echo $x . "/" . $y;
    return true;
  } else {
    return false;
  }
}

//we're now *outside* of the function, and in mainline logic

//setup a variable to hold the return value of the function
//initialize it to false so that the first loop executes
$foundEquation = false;


//execute the function in a loop until we find
//the right equation
while(!$foundEquation) { 
  $foundEquation = foo();
}

Does that answer your question? Let me know if you have any trouble understanding what's happening here. I'm happy to clarify anything about this code.

客…行舟 2024-10-14 19:43:13

你的问题是你没有重新声明 $x 和 $y 。假设,这个应该进入无限递归。如果你想递归地执行此操作,则必须在 foo() 函数中定义 $x 和 $y 。确保变量是在 if() 语句之外和之前声明的。

祝你好运!
丹尼斯·M.

Your problem is that you're not redeclaring $x and $y. Hypothetically, this should go into infinite recursion. If you want to do this recursively, you're going to have to define $x and $y in your foo() function. Make sure the variables are declared outside and before your if() statement.

Good luck!
Dennis M.

软糖 2024-10-14 19:43:13

在您发布的“它不起作用”链接中,您没有调用函数 foo()。

一些注意事项:

  • y 可能为零,因此您可能会收到“除以零”错误。
  • 您正在使用递归,并且大多数时候您的代码都会进入 else 情况。如果嵌套深度变大,则可能会遇到堆栈溢出。

In the "It doesn't work" link that you posted, you're not calling the function foo().

A couple of notes:

  • y may be zero so you might get a "divide by zero" error.
  • You are using recursion and a majority of the time your code would go into the else case. If your nesting depth gets large, you might encounter a stack overflow.
み青杉依旧 2024-10-14 19:43:13

Paxdiablo 走在正确的轨道上,但这可能是您想要的:

<?php
    function foo() {
        do
        {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        while ($x % $y != 0);

        echo $x . "/" . $y;
    }
?>

这将循环执行 do { } while 内的代码,直到 while 条件为 false。 while 和 do while 之间的区别在于,代码在检查条件之前执行。

Paxdiablo is on the right track but this is what you probably want:

<?php
    function foo() {
        do
        {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        while ($x % $y != 0);

        echo $x . "/" . $y;
    }
?>

This will loop executing the code inside the do { } while until the while condition to false. The difference between a while and a do while is that the code is executed before the condition is checked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文