简体   繁体   English

在此代码中查找错误。此程序是用 PHP 编写的

[英]Find Error in this code.this program is written in PHP

<?php 
   echo "Enter Month:";
    $m=trim(fgets(STDIN)); 

    echo "Enter Day:";
    $d=trim(fgets(STDIN));
    //{Write your code here

   if($m>=3 && $m<=6)
   {
       if($d>=20){
           echo"Spring";
       }

   }
   else
   {
       echo"Not Spring";
   }





    //}
    exit;
?>

Find error in this code The duration between March 20 (inclusive) and June 20 (inclusive) is Spring time.在此代码中查找错误 3 月 20 日(含)和 6 月 20 日(含)之间的持续时间为春季。 Write a program which takes month and day as positive integer input and shows whether its a spring time or not.编写一个程序,将月和日作为正整数输入并显示其是否为春季时间。

This looks a lot like an assignement for class or something, you would gain very little from asking (and not even asking nicely) someone else to do it....这看起来很像课堂作业或其他东西,你从要求(甚至不是很好地要求)别人做这件事中获得的收益很少......

That being said, I'm bored, so i'll guide you a little:话虽如此,我很无聊,所以我会指导你一点:

if($m>=3 && $m<=6)
{
    if($d>=20){
        echo"Spring";
    }
}

This logic is flawed.这个逻辑是有缺陷的。 This will return "Spring" only the days 20 to 31 for the months 3 to 6, which means that something like April 1st (01/04) will not return Spring.这将仅在 3 到 6 个月的 20 到 31 天返回“Spring”,这意味着像 4 月 1 日 (01/04) 这样的日期不会返回 Spring。

What your if statement should look like is something like `It's the 3rd month and the 20th or later, or it's the 4th month, or it's the 5th month, or it's the 6th month and the 20th or later':您的 if 语句应该类似于“现在是第 3 个月和第 20 天或之后,或者是第 4 个月,或者是第 5 个月,或者是第 6 个月和第 20 天或之后”:

if(($m == 3 && $d >= 20) || ($m == 4) || ($m == 5) || ($m == 6 && $d <= 20))

Extra:额外的:

Judging by your code above, the following might be too advanced, but I want to specify it because handling date as string is overall a bad bad idea and leads to disasters most of the time.根据您上面的代码判断,以下内容可能太高级了,但我想指定它,因为将日期作为字符串处理总体上是一个坏主意,并且在大多数情况下会导致灾难。 If you don't get it, put it aside for now.如果你没有得到它,暂时把它放在一边。

The best way to handle it is to threat those as real dates rather than integers using the PHP DateTime object:处理它的最好方法是使用 PHP DateTime对象威胁那些作为真实日期而不是整数:

$beginingSpring = Datetime::createFromFormat('m-d', '03-20'); // March 20th.
$endSpring = Datetime::createFromFormat('m-d', '06-20'); // June 20th.
$date = Datetime::createFromFormat('m-d', $m.'-'.d); // Entered date

if($date >= $beginingSpring && $date <= $endSpring){ 
    echo 'Spring'; 
}else{ 
    echo 'Not spring'; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM