page contents

C#将“double”转换为“ushort”

本文讲述了C#将“double”转换为“ushort”!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

attachments-2022-10-DiydT6co633f859fbc56d.png

本文讲述了C#将“double”转换为“ushort”!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

ushort是一个16位变量,可以保存0到65535之间的整个值。一个double是一个8字节变量,可以容纳很多值,包括分数。

因此,如果您将double转换为ushort,您可能会丢失数据。 这就是为什么没有明确指示系统不会让你这么做的原因。

最简单的方法是使用强制转换运算符:例如

double d = 99.99;
ushort u = (ushort)d;

或者您可以使用明确舍入或截断双精度的数学函数之一来强制转换它,但它们会返回双精度数,因此您仍需要强制转换。

您应该首先考虑为什么要将double值放入ushort类型中。 设计正确的行为远比将圆形挂钉压成方形夹具更重要,因为你可以。


An ushort is a 16-bit variable that can hold whole values between 0 and 65535. A double is a 8-byte variable that can hold .. lots of values, including fractions.

So if you convert the double to a ushort you will probably lose data. This is why the system will not let you do it without explicit instruction.

The easiest way to cast is using the cast operators: eg

double d = 99.99;
ushort u = (ushort)d;

or you can cast it using one of the maths functions that explicitly round or truncate the double, but they return doubles so you'll still have to cast.

You should consider why you want to put a double value into a ushort type first. Designing for correct behaviour is far more important than squishing a round peg into a square hold just because you can.


更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg



  • 发表于 2022-10-07 09:49
  • 阅读 ( 723 )
  • 分类:C/C++开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
轩辕小不懂
轩辕小不懂

2403 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. Pack 1131 文章
  3. 小柒 1046 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章