如何将size_t转换为double或int C ++ [英] how to cast the size_t to double or int C++
问题描述
我的问题是
我有一个size_t数据,但现在我想将其转换为double或int。
I have a size_t data, but now I want to convert it to double or int.
如果我做了
size_t data = 99999999;
int convertdata = data;
编译器将报告警告。因为它可能溢出。
the compiler will report warning. because it maybe overflow.
你有一些方法像boost或其他方法来执行转换吗?
Do you have some method like the boost or some other method to do the convert?
推荐答案
演员, Blaz Bratanic建议:
size_t data = 99999999;
int convertdata = static_cast<int>(data);
很可能会使警告静音(虽然原则上编译器可以警告任何它喜欢,有一个转换)。
is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).
但它不能解决警告告诉你的问题,即从 size_t
到
int
真的可能溢出。
But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t
to int
really could overflow.
如果可能,设计你的程序,需要将 size_t
值转换为 int
。只需将它存储在 size_t
变量(如你已经做过的那样)。
If at all possible, design your program so you don't need to convert a size_t
value to int
. Just store it in a size_t
variable (as you've already done) and use that.
转换为 double
不会导致溢出,但对于非常大的 size_t
值,可能会导致精度损失。再次,将 size_t
转换为 double
没有什么意义;你最好把这个值保存在 size_t
变量中。
Converting to double
will not cause an overflow, but it could result in a loss of precision for a very large size_t
value. Again, it doesn't make a lot of sense to convert a size_t
to a double
; you're still better off keeping the value in a size_t
variable.
这篇关于如何将size_t转换为double或int C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!