C++类型转换是否自动进行舍入?

问题描述 投票:0回答:1

我有以下代码:

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

int main(){
    uint64_t value = uint64_t(1693829987930866899) / 1000.0;
    std::string str_value = std::to_string(value);
    printf("value=%lu, str_value=%s len=%lu\n", value, str_value.c_str(), str_value.size());
}

输出:

value=1693829987930867, str_value=1693829987930867 len=16

预期输出是1693829987930866,但我得到1693829987930867。g++编译器会自动进行舍入吗?

c++ type-conversion g++ uint64
1个回答
0
投票

请参阅此处的警告:https://godbolt.org/z/vzE3976hP - 它说的是@n.m.couldbeanAI所说的 - 它正在转换为双倍

这就是你想要的(注意额外的演员)

https://godbolt.org/z/66Wxj6vvj

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;

int main(){
    uint64_t value = uint64_t(1693829987930866899) / uint64_t(1000.0);
    std::string str_value = std::to_string(value);
    printf("value=%lu, str_value=%s len=%lu\n", value, str_value.c_str(), str_value.size());
}

值=1693829987930866,str_value=1693829987930866 长度=16

© www.soinside.com 2019 - 2024. All rights reserved.