gpt4 book ai didi

c# - Float to decimal 和 decimal to float。一般所有转换

转载 作者:行者123 更新时间:2023-11-30 21:53:54 30 4
gpt4 key购买 nike

我正在学习 C#。我完全不知道为什么以及这里的正确答案是什么。我搜索了很多,但一无所获。人们解释,却找不到解释。正确答案是什么?为什么?

在以下哪些转换过程中可能会出现精度损失?

  • 一个。将整数转换为 float
  • b。将浮点型转换为长型
  • c。将 long 转换为 int
  • d。将 int 转换为 long
  • e。将 float 转换为小数
  • f.将小数转换为 float

为什么 float to decimal 和 decimal to float 都可能丢失精度转换..?

最佳答案

During which of the following conversions might there be a loss of precision?

a. Converting an int to a float

int 具有 32 位精度,完全用于数字的非小数部分。 float 有 32 位精度,但其中一些位用于指数,剩下不到 32 位来表示尾数。因此,有些数字可以表示为 int 但不能表示为 float

例如:

int i = int.MaxValue; // = 2147483647
float f = (float)i; // = 2147484000 --> lost last three digits!

b. Converting a float to a long

我希望您很容易看出从浮点到整数类型的转换是如何丢失精度的。

c. Converting a long to an int

您的书没有将此作为问题提及,这表明它区分精度损失和准确性损失(仅供引用)。

在 C# 中,long 是 64 位,而 int 只有 32 位。任何大于 int.MaxValue 的数字(即 2147483647)都不能用 int 表示,但许多这样的数字可以用 long 表示。将任何此类数字从 long 转换为 int 将导致准确性下降,即生成的数字甚至不接近正确的数字。

可以说它失去了精度,但我猜你的书关注的是精度丢失的情况?

d. Converting an int to a long

我假设您理解为什么这不会失去精度(或准确度)。

e. Converting a float to a decimal
f. Converting a decimal to a float

Why are both float to decimal and decimal to float a possible loss of precision conversion..?

decimalfloat 更容易解释:我们之所以首先使用 decimal 是因为普通的 float 数字类型根本无法表示 decimal 可以且对常见类型的计算(例如货币计算)和其他值很重要的某些值 decimal也不能代表它至少可以更接近地代表他们。

例如:

float f = 1f / 3;
decimal d = 1M / 3;
float f2 = (float)d;

在上面,变量f的值为0.333333343,而变量d的值为0.33333333333333333333333333333。两者都不精确(因为 1/3 是一个循环小数,它不能用有限的计算机表示),但是 decimal 版本更接近正确答案。

同样,从 decimal 转换回 float 会导致精度损失,因为变量 f2 的值与f 做了:0.333333343

但是如何将 float 转换为 decimal

嗯,虽然 decimalfloat 有更多的精度(大约 28 比 7),float 类型支持带有震级小至 1.401298E-45(即 float.Epsilon)。但是decimal不能表示这么小的数(只能表示1E-28这样小的数)。转换大小小于decimal 可以表示的float 数字将导致值0,丢失那些有效的小数位。

换句话说:虽然 float 只有 7 位精度而 decimal 有 28 位,float 可以将这些数字移动得更远小数点右边比 decimal 可以,允许 float 中的数字比 decimal 可以表示的更小。

因此,无论哪种方式都可能会失去精度(这就是为什么在 C# 中这些类型之间没有隐式转换的原因……它仅在没有信息丢失时才提供隐式转换)。

另见:
Explicit Numeric Conversions Table (C# Reference)
Single Structure
Decimal Structure
Difference between Decimal, Float and Double in .NET?

关于c# - Float to decimal 和 decimal to float。一般所有转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605776/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com