C++双精度为 1079574528 或 0

C++ double is either 1079574528 or 0

本文关键字:1079574528 双精度 C++      更新时间:2023-10-16

我的代码如下所示:

// in Player.cpp
Player::Player() {
    hp = 100;
    pos = vec(50, 50);
    printf("created player with %d hp on %d:%dn", hp, pos.x, pos.y);
}
// in Game.h
Player *player;
// in Game.cpp
player = new Player();

并且输出始终是"创建播放器,在 1079574528:0 上具有 0 hp"但是,当游戏运行时,x 和 y 位置是正确的。

您正在获得输出,因为您在 printf() 中使用 %d 作为双精度。您应该使用%f

如果你使用%f,你会得到正确的输出(假设pos = vec(50, 50);不会导致任何问题)。

另外,由于您使用的是c ++,因此您可以使用

std::cout << "created player with " << hp << " hp on " << pos.x << " : " << pos.y << std::endl ;

由于您是用C++编写的,请使用C++。

Player::Player() {
    hp = 100;
    pos = vec(50, 50);
    std::cout << "created player with hp=" << hp << " on X:" << pos.x << ",Y:" << pos.y << std::endl;
}