如何将size_t转换为double或int C ++ [英] How to cast the size_t to double or int C++

查看:345
本文介绍了如何将size_t转换为double或int C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是



我有一个size_t数据,但现在我想将其转换为double或int。



如果我做了像

  size_t data = 99999999; 
int convertdata = data;

编译器将报告警告。因为它可能会溢出。



你有一些方法像boost或其他方法做转换吗?

解决方案

演员,作为Blaz Bratanic建议

  size_t data = 99999999; 
int convertdata = static_cast< int>(data);

可能会使警告沉默(尽管原则上编译器可以警告任何它喜欢的内容,即使有一个演员)



但是它并没有解决警告告诉你的问题,即从 size_t int 真的可以溢出。



如果可能的话,设计你的程序,让你需要将 size_t 值转换为 int 。只需将它存储在 size_t 变量(如您已经完成)中,并使用它。



转换为 double 不会导致溢出,但是可能导致非常大的 size_t 值的精度损失。再次,将 size_t 转换为 double 并不重要;你还是把价值保持在一个 size_t 变量中。


My question is that

I have a size_t data, but now I want to convert it to double or int.

If I do something like

 size_t data = 99999999;
 int convertdata = data;

the compiler will report warning. because it maybe overflow.

Do you have some method like the boost or some other method to do the convert?

解决方案

A cast, as Blaz Bratanic suggested:

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).

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.

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆