简体   繁体   English

同一算法在C和PHP中的运行方式不同

[英]Same algorithm runs differently in C and PHP

I was practicing a problem on CodeChef.com. 我在CodeChef.com上正在练习一个问题。

https://www.codechef.com/problems/CHOPRT --> Link to the question I was solving. https://www.codechef.com/problems/CHOPRT- >链接到我正在解决的问题。

I successfully solved the question using C. 我使用C成功解决了这个问题。

My C code: 我的C代码:

#include <stdio.h>

int main() {

    int t;
    int num1;
    int num2;


    scanf("%d", &t);

    while(t--) {

        scanf("%d %d", &num1, &num2);
        if(num1 > num2)
            printf(">");
        else if(num1 < num2)
            printf("<");
        else
            printf("=");
        printf("\n");           
    }

    return 0;
}  

But I am not able to solve it using PHP: 但是我无法使用PHP解决它:

My PHP code: 我的PHP代码:

<?php

    $t = intval(fgets(STDIN));

    while($t--) {

        $line = split(" ", trim(fgets(STDIN)));
        $num1 = intval($line[0]);
        $num2 = intval($line[1]);

        if($num1 < $num2)
            print("<");
        else if($num1 > $num2)
            print(">");
        else
            print("="); 
        print("\n");        
    }
?>  

Though both the programs run perfectly on my MacBook Pro, the PHP code is not run on codechef.com and gives a WA (Wrong Answer). 尽管这两个程序都可以在我的MacBook Pro上完美运行,但PHP代码未在codechef.com上运行,并给出了WA (错误答案)。 C code is run perfectly though and that to within 0.00 seconds. C代码可以完美运行,并且运行时间在0.00秒以内。

Please, enlighten me with the difference between the two respective codes, which I personally believe, should be working the same, and also produce the same output. 请给我启发,我个人认为这两个代码之间的区别应该相同,并且产生相同的输出。

Often i hear that some testcases are erroneous.I have a corner case for you which would give perfect result for your C code but not for your PHP 我经常听到一些测试用例是错误的。我为您准备了一个案例,它将为您的C代码而不是您的PHP提供完美的结果

Do this : 做这个 :

1
10  10 

Notice there is more than one space between the two digits. 请注意,两位数之间有一个以上的空格。

I tested it here . 在这里测试 Instead of the expected output which is: 而不是预期的输出是:

=

your Output is: 您的输出是:

>

Though C would pass this test case as scanf searches for the next integer number you type, PHP would fail since there is more than one space. 尽管C会在scanf搜索您键入的下一个整数时通过此测试用例,但PHP将失败,因为存在多个空格。 To make it work in PHP i did suggest you to code in such a way that the spaces between the two numbers dont affect your expected output. 为了使它在PHP中工作,我确实建议您以这样的方式进行编码:两个数字之间的空格不会影响您的预期输出。

That's the only way i believe your PHP Code won't work.If this indeed was the issue it's not your fault! 这是我相信您的PHP代码无法正常工作的唯一方法。如果确实是问题所在,那不是您的错!

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

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