简体   繁体   中英

Same algorithm implementation has different retults in Python and C++?

This python code works properly and produces proper output:

def fib(x):
    v = 1
    u = 0
    for x in xrange(1,x+1):
        t = u + v
        u = v
        v = t
    return v

But when I write the same code in C++ it gives me a different and impossible result.

int fib(int x)
{
    int v = 1;
    int u = 0;
    int t;
    for (int i = 1; i != x + 1; i++)
    {
        t = u + v;
        u = v;
        v = t;
    }
    return v;
}

I'm still learning c++. Thanks!

Edit: C++ outputs -1408458269.
Python outputs 20365011074 when x = 50.

For what input? Python has integers of unlimited (memory limited) size, C++'s int usually is a four byte integer, so you'll likely have overflow.

The largest Fibonacci number representable with a signed 32-bit integer type is fib(46) = 1836311903 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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