微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么在 C++ 中以 64 位编译时会出现 32 位溢出?

如何解决为什么在 C++ 中以 64 位编译时会出现 32 位溢出?

所以,我决定测试一个新的 C++ 海龟风格的图形库。我决定通过制作斐波那契螺旋来测试它。但是,在运行程序时,它会停在中间。我检查了发生了什么,斐波那契值已经反转为-2147483647,就好像它是用 32 位编译的一样。有人可以帮忙吗?我在 Windows 上用 g++ 编译它。 注意:我使用向量来存储值。 这是我的代码

//Includes and namespaces
#include "Cturtle.hpp"
#include<iostream>
namespace ct = cturtle;

std::vector<long int> fibonacci = {1,2}; //This vector stores the fib sequence
ct::TurtleScreen scr; //Create a new Screen
ct::Turtle turtle(scr); //Create a new turtle on the screen

int main() {
    turtle.speed(ct::TS_FASTEST); //Set the turtle's speed to max
    
    while(true) {
        for(int i = 0; i < fibonacci.back(); i++) {
            
            fibonacci.push_back(fibonacci.back() + fibonacci.back()-1); //Add a new value to the fibonacci vector based off the prevIoUs two
            std::cout << fibonacci.back() << '\n'; //This is here for debug
            turtle.forward(1); //Move the turtle 1 step forward
            turtle.right(90 / fibonacci.back()); //Turn according to 90 divided by the current fibonacci value
        }
    }
}

解决方法

MinGW 使用 MSVC 友好的 LLP64 data model

在 LLP64 中,intlong int 都是 32 位,与平台位数无关(32/64 位)。

要获取 64 位数据类型,请使用 long longint64_t

例如std::vector<long long>。还有这里:for(long long i = 0; ...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。