简体   繁体   English

C程序在OSX和Windows上给出不同的结果

[英]C program giving different results on OSX and windows

I wrote a recursive function in C to reverse an integer (123 -> 321) which worked fine when I ran it on my Mac, but behaves strangely when my instructor ran it on her computer running Windows. 我在C中写了一个递归函数来反转一个整数(123 - > 321),当我在我的Mac上运行它时工作正常,但是当我的教练在运行Windows的计算机上运行它时表现得很奇怪。

int rev(int num)
{
    int base;

    if (num < 10) return (num); 

    base = pow(10,(int)log10(num));
    return(rev(num/10)+num%10*base);
}

For example, on OSX calling rev(8765) returns 5678, On Windows, rev(8765) returns 5672. I don't have access to a Windows machine to try to run the program in debug mode, so I've been having a hard time trying to guess what the issue is. 例如,在OSX上调用rev(8765)返回5678,在Windows上,rev(8765)返回5672.我无法访问Windows机器以尝试在调试模式下运行程序,所以我一直在很难想到问题是什么。 I would greatly appreciate any insight! 我非常感谢任何见解!

Environment: 环境:

I am using using OSX 10.8 and GCC 4.2. 我使用的是OSX 10.8和GCC 4.2。 I'm pretty sure my instructor is using MinGW as her compiler. 我很确定我的导师正在使用MinGW作为她的编译器。

pow and log10 are not required to be correctly rounded; powlog10不需要正确舍入; the results produced by them can and will differ between platforms, even for cases that “should be” exact like in your example. 它们产生的结果可以并且将在平台之间有所不同,即使对于“应该”与您的示例中完全相同的情况也是如此。 In this case, OS X produces a more accurate result than Windows, which results in errors that show up only in the Windows output. 在这种情况下,OS X会产生比Windows更准确的结果,这会导致仅在Windows输出中显示的错误。

A much better solution would be to use repeated division and multiplication by 10 in integer, and not use floating-point at all (there is a very clean recursive solution similar to yours, without requiring that you compute base ). 一个更好的解决办法是由10整数使用重复的除法和乘法,而不是使用浮点在所有的(有类似你一个非常干净的递归解决方案,而不需要你计算base )。


As an aside, a mini-rant: It's shameful that so many math libraries do not correctly handle small powers of ten and two in log10 , log2 , exp2 and pow . 顺便说一句,一个迷你咆哮:很多数学库在log10log2exp2pow没有正确处理10和2的小功率是可耻的 It is not hard to design these functions such that they do the “right thing” for these cases, and it can be done without adversely affecting performance of other cases. 设计这些功能并不难,因为它们为这些情况做了“正确的事情”,并且可以在不对其他情况的性能产生不利影响的情况下完成。 While it is not required by the standard, it is a simple thing to do and it helps to save inexperienced programmers from (exceptionally common) errors like this one. 虽然标准不需要它,但这是一件简单的事情,它有助于拯救没有经验的程序员(如此常见)错误。

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

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