小编Rad*_*ski的帖子

当转换为double然后返回uint64_t时,strtoull()的输出会失去精度。

考虑以下:

#include <iostream>
#include <cstdint>

int main() {
   std::cout << std::hex
      << "0x" << std::strtoull("0xFFFFFFFFFFFFFFFF",0,16) << std::endl
      << "0x" << uint64_t(double(std::strtoull("0xFFFFFFFFFFFFFFFF",0,16))) << std::endl
      << "0x" << uint64_t(double(uint64_t(0xFFFFFFFFFFFFFFFF))) << std::endl;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

哪些打印:

0xffffffffffffffff
0x0
0xffffffffffffffff
Run Code Online (Sandbox Code Playgroud)

第一个数字只是将ULLONG_MAX,从字符串转换为的结果,uint64_t按预期方式运行。

但是,如果我将结果转换为double,然后又转换为uint64_t,则它将输出0第二个数字。

通常,我将其归因于浮点数的精度不准确,但令我感到困惑的是,如果我将ULLONG_MAXfrom转换uint64_tdouble,然后再转换回uint64_t,结果是正确的(第三个数字)。

为什么第二和第三结果之间存在差异?

编辑(@Radoslaw Cybulski撰写)有关此处发生的另一个问题,请尝试以下代码:

#include <iostream>
#include <cstdint>
using namespace std;

int main() {
    uint64_t z1 = std::strtoull("0xFFFFFFFFFFFFFFFF",0,16);
    uint64_t z2 = 0xFFFFFFFFFFFFFFFFull;
    std::cout << …
Run Code Online (Sandbox Code Playgroud)

c++ precision strtol strtoull

8
推荐指数
1
解决办法
73
查看次数

为什么矢量会发生这种情况

我一直在编写代码以将书添加到库中。当我将书添加到库中并尝试显示它时,库中什么都没有存储(显示)

在这里,我将库可以容纳的最大书籍数量设置为
100。int maxbooks = 100; 向量图书馆(maxbooks); 当我删除“(maxbooks)”时,代码工作正常。但是我不明白为什么?

#include <iostream>
#include <vector> 
#include <string>

using namespace std;

//struct model a book 
    struct book {
    string authorname;
    string bookname;
}; //struct ends here 

//function to display number of books in the library
void displayLibrary(vector <book> &cmini_library,int cnum_of_books);

//function to add books to the library;
void add (vector <book> &cminilibrary,book dummylibrary,int &num_of_books);

int main() {
    int option;
    int curr_num_of_books = 0; //current number of books in the library
    int maxbooks = 100; …
Run Code Online (Sandbox Code Playgroud)

c++ vector

0
推荐指数
1
解决办法
79
查看次数

标签 统计

c++ ×2

precision ×1

strtol ×1

strtoull ×1

vector ×1