Single 结构
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示一个单精度浮点数。
public value class float : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public value class float : IComparable, IComparable<float>, IConvertible, IEquatable<float>, ISpanFormattable
public value class float : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, System::Numerics::IAdditionOperators<float, float, float>, System::Numerics::IAdditiveIdentity<float, float>, System::Numerics::IBinaryFloatingPointIeee754<float>, System::Numerics::IBinaryNumber<float>, System::Numerics::IBitwiseOperators<float, float, float>, System::Numerics::IComparisonOperators<float, float, bool>, System::Numerics::IDecrementOperators<float>, System::Numerics::IDivisionOperators<float, float, float>, System::Numerics::IEqualityOperators<float, float, bool>, System::Numerics::IExponentialFunctions<float>, System::Numerics::IFloatingPoint<float>, System::Numerics::IFloatingPointConstants<float>, System::Numerics::IFloatingPointIeee754<float>, System::Numerics::IHyperbolicFunctions<float>, System::Numerics::IIncrementOperators<float>, System::Numerics::ILogarithmicFunctions<float>, System::Numerics::IMinMaxValue<float>, System::Numerics::IModulusOperators<float, float, float>, System::Numerics::IMultiplicativeIdentity<float, float>, System::Numerics::IMultiplyOperators<float, float, float>, System::Numerics::INumber<float>, System::Numerics::INumberBase<float>, System::Numerics::IPowerFunctions<float>, System::Numerics::IRootFunctions<float>, System::Numerics::ISignedNumber<float>, System::Numerics::ISubtractionOperators<float, float, float>, System::Numerics::ITrigonometricFunctions<float>, System::Numerics::IUnaryNegationOperators<float, float>, System::Numerics::IUnaryPlusOperators<float, float>
public value class float : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, IUtf8SpanParsable<float>, System::Numerics::IAdditionOperators<float, float, float>, System::Numerics::IAdditiveIdentity<float, float>, System::Numerics::IBinaryFloatingPointIeee754<float>, System::Numerics::IBinaryNumber<float>, System::Numerics::IBitwiseOperators<float, float, float>, System::Numerics::IComparisonOperators<float, float, bool>, System::Numerics::IDecrementOperators<float>, System::Numerics::IDivisionOperators<float, float, float>, System::Numerics::IEqualityOperators<float, float, bool>, System::Numerics::IExponentialFunctions<float>, System::Numerics::IFloatingPoint<float>, System::Numerics::IFloatingPointConstants<float>, System::Numerics::IFloatingPointIeee754<float>, System::Numerics::IHyperbolicFunctions<float>, System::Numerics::IIncrementOperators<float>, System::Numerics::ILogarithmicFunctions<float>, System::Numerics::IMinMaxValue<float>, System::Numerics::IModulusOperators<float, float, float>, System::Numerics::IMultiplicativeIdentity<float, float>, System::Numerics::IMultiplyOperators<float, float, float>, System::Numerics::INumber<float>, System::Numerics::INumberBase<float>, System::Numerics::IPowerFunctions<float>, System::Numerics::IRootFunctions<float>, System::Numerics::ISignedNumber<float>, System::Numerics::ISubtractionOperators<float, float, float>, System::Numerics::ITrigonometricFunctions<float>, System::Numerics::IUnaryNegationOperators<float, float>, System::Numerics::IUnaryPlusOperators<float, float>
public value class float : IComparable, IConvertible, IFormattable
public value class float : IComparable, IComparable<float>, IEquatable<float>, IFormattable
public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public readonly struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public readonly struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, ISpanFormattable
public readonly struct Single : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, System.Numerics.IAdditionOperators<float,float,float>, System.Numerics.IAdditiveIdentity<float,float>, System.Numerics.IBinaryFloatingPointIeee754<float>, System.Numerics.IBinaryNumber<float>, System.Numerics.IBitwiseOperators<float,float,float>, System.Numerics.IComparisonOperators<float,float,bool>, System.Numerics.IDecrementOperators<float>, System.Numerics.IDivisionOperators<float,float,float>, System.Numerics.IEqualityOperators<float,float,bool>, System.Numerics.IExponentialFunctions<float>, System.Numerics.IFloatingPoint<float>, System.Numerics.IFloatingPointConstants<float>, System.Numerics.IFloatingPointIeee754<float>, System.Numerics.IHyperbolicFunctions<float>, System.Numerics.IIncrementOperators<float>, System.Numerics.ILogarithmicFunctions<float>, System.Numerics.IMinMaxValue<float>, System.Numerics.IModulusOperators<float,float,float>, System.Numerics.IMultiplicativeIdentity<float,float>, System.Numerics.IMultiplyOperators<float,float,float>, System.Numerics.INumber<float>, System.Numerics.INumberBase<float>, System.Numerics.IPowerFunctions<float>, System.Numerics.IRootFunctions<float>, System.Numerics.ISignedNumber<float>, System.Numerics.ISubtractionOperators<float,float,float>, System.Numerics.ITrigonometricFunctions<float>, System.Numerics.IUnaryNegationOperators<float,float>, System.Numerics.IUnaryPlusOperators<float,float>
public readonly struct Single : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, IUtf8SpanParsable<float>, System.Numerics.IAdditionOperators<float,float,float>, System.Numerics.IAdditiveIdentity<float,float>, System.Numerics.IBinaryFloatingPointIeee754<float>, System.Numerics.IBinaryNumber<float>, System.Numerics.IBitwiseOperators<float,float,float>, System.Numerics.IComparisonOperators<float,float,bool>, System.Numerics.IDecrementOperators<float>, System.Numerics.IDivisionOperators<float,float,float>, System.Numerics.IEqualityOperators<float,float,bool>, System.Numerics.IExponentialFunctions<float>, System.Numerics.IFloatingPoint<float>, System.Numerics.IFloatingPointConstants<float>, System.Numerics.IFloatingPointIeee754<float>, System.Numerics.IHyperbolicFunctions<float>, System.Numerics.IIncrementOperators<float>, System.Numerics.ILogarithmicFunctions<float>, System.Numerics.IMinMaxValue<float>, System.Numerics.IModulusOperators<float,float,float>, System.Numerics.IMultiplicativeIdentity<float,float>, System.Numerics.IMultiplyOperators<float,float,float>, System.Numerics.INumber<float>, System.Numerics.INumberBase<float>, System.Numerics.IPowerFunctions<float>, System.Numerics.IRootFunctions<float>, System.Numerics.ISignedNumber<float>, System.Numerics.ISubtractionOperators<float,float,float>, System.Numerics.ITrigonometricFunctions<float>, System.Numerics.IUnaryNegationOperators<float,float>, System.Numerics.IUnaryPlusOperators<float,float>
[System.Serializable]
public struct Single : IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public struct Single : IComparable, IComparable<float>, IEquatable<float>, IFormattable
type single = struct
interface IConvertible
interface IFormattable
type single = struct
interface IConvertible
interface ISpanFormattable
interface IFormattable
type single = struct
interface IConvertible
interface IFormattable
interface IParsable<single>
interface ISpanFormattable
interface ISpanParsable<single>
interface IAdditionOperators<single, single, single>
interface IAdditiveIdentity<single, single>
interface IBinaryFloatingPointIeee754<single>
interface IBinaryNumber<single>
interface IBitwiseOperators<single, single, single>
interface IComparisonOperators<single, single, bool>
interface IEqualityOperators<single, single, bool>
interface IDecrementOperators<single>
interface IDivisionOperators<single, single, single>
interface IIncrementOperators<single>
interface IModulusOperators<single, single, single>
interface IMultiplicativeIdentity<single, single>
interface IMultiplyOperators<single, single, single>
interface INumber<single>
interface INumberBase<single>
interface ISubtractionOperators<single, single, single>
interface IUnaryNegationOperators<single, single>
interface IUnaryPlusOperators<single, single>
interface IExponentialFunctions<single>
interface IFloatingPointConstants<single>
interface IFloatingPoint<single>
interface ISignedNumber<single>
interface IFloatingPointIeee754<single>
interface IHyperbolicFunctions<single>
interface ILogarithmicFunctions<single>
interface IPowerFunctions<single>
interface IRootFunctions<single>
interface ITrigonometricFunctions<single>
interface IMinMaxValue<single>
type single = struct
interface IConvertible
interface IFormattable
interface IParsable<single>
interface ISpanFormattable
interface ISpanParsable<single>
interface IAdditionOperators<single, single, single>
interface IAdditiveIdentity<single, single>
interface IBinaryFloatingPointIeee754<single>
interface IBinaryNumber<single>
interface IBitwiseOperators<single, single, single>
interface IComparisonOperators<single, single, bool>
interface IEqualityOperators<single, single, bool>
interface IDecrementOperators<single>
interface IDivisionOperators<single, single, single>
interface IIncrementOperators<single>
interface IModulusOperators<single, single, single>
interface IMultiplicativeIdentity<single, single>
interface IMultiplyOperators<single, single, single>
interface INumber<single>
interface INumberBase<single>
interface ISubtractionOperators<single, single, single>
interface IUnaryNegationOperators<single, single>
interface IUnaryPlusOperators<single, single>
interface IUtf8SpanFormattable
interface IUtf8SpanParsable<single>
interface IExponentialFunctions<single>
interface IFloatingPointConstants<single>
interface IFloatingPoint<single>
interface ISignedNumber<single>
interface IFloatingPointIeee754<single>
interface IHyperbolicFunctions<single>
interface ILogarithmicFunctions<single>
interface IPowerFunctions<single>
interface IRootFunctions<single>
interface ITrigonometricFunctions<single>
interface IMinMaxValue<single>
[<System.Serializable>]
type single = struct
interface IFormattable
interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type single = struct
interface IFormattable
interface IConvertible
type single = struct
interface IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IConvertible, IEquatable(Of Single), IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IConvertible, IEquatable(Of Single), ISpanFormattable
Public Structure Single
Implements IAdditionOperators(Of Single, Single, Single), IAdditiveIdentity(Of Single, Single), IBinaryFloatingPointIeee754(Of Single), IBinaryNumber(Of Single), IBitwiseOperators(Of Single, Single, Single), IComparable(Of Single), IComparisonOperators(Of Single, Single, Boolean), IConvertible, IDecrementOperators(Of Single), IDivisionOperators(Of Single, Single, Single), IEqualityOperators(Of Single, Single, Boolean), IEquatable(Of Single), IExponentialFunctions(Of Single), IFloatingPoint(Of Single), IFloatingPointConstants(Of Single), IFloatingPointIeee754(Of Single), IHyperbolicFunctions(Of Single), IIncrementOperators(Of Single), ILogarithmicFunctions(Of Single), IMinMaxValue(Of Single), IModulusOperators(Of Single, Single, Single), IMultiplicativeIdentity(Of Single, Single), IMultiplyOperators(Of Single, Single, Single), INumber(Of Single), INumberBase(Of Single), IParsable(Of Single), IPowerFunctions(Of Single), IRootFunctions(Of Single), ISignedNumber(Of Single), ISpanParsable(Of Single), ISubtractionOperators(Of Single, Single, Single), ITrigonometricFunctions(Of Single), IUnaryNegationOperators(Of Single, Single), IUnaryPlusOperators(Of Single, Single)
Public Structure Single
Implements IAdditionOperators(Of Single, Single, Single), IAdditiveIdentity(Of Single, Single), IBinaryFloatingPointIeee754(Of Single), IBinaryNumber(Of Single), IBitwiseOperators(Of Single, Single, Single), IComparable(Of Single), IComparisonOperators(Of Single, Single, Boolean), IConvertible, IDecrementOperators(Of Single), IDivisionOperators(Of Single, Single, Single), IEqualityOperators(Of Single, Single, Boolean), IEquatable(Of Single), IExponentialFunctions(Of Single), IFloatingPoint(Of Single), IFloatingPointConstants(Of Single), IFloatingPointIeee754(Of Single), IHyperbolicFunctions(Of Single), IIncrementOperators(Of Single), ILogarithmicFunctions(Of Single), IMinMaxValue(Of Single), IModulusOperators(Of Single, Single, Single), IMultiplicativeIdentity(Of Single, Single), IMultiplyOperators(Of Single, Single, Single), INumber(Of Single), INumberBase(Of Single), IParsable(Of Single), IPowerFunctions(Of Single), IRootFunctions(Of Single), ISignedNumber(Of Single), ISpanParsable(Of Single), ISubtractionOperators(Of Single, Single, Single), ITrigonometricFunctions(Of Single), IUnaryNegationOperators(Of Single, Single), IUnaryPlusOperators(Of Single, Single), IUtf8SpanParsable(Of Single)
Public Structure Single
Implements IComparable, IConvertible, IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IEquatable(Of Single), IFormattable
- 继承
- 属性
- 实现
-
IComparable IComparable<Single> IConvertible IEquatable<Single> IFormattable ISpanFormattable IComparable<TSelf> IEquatable<TSelf> IParsable<Single> IParsable<TSelf> ISpanParsable<Single> ISpanParsable<TSelf> IAdditionOperators<Single,Single,Single> IAdditionOperators<TSelf,TSelf,TSelf> IAdditiveIdentity<Single,Single> IAdditiveIdentity<TSelf,TSelf> IBinaryFloatingPointIeee754<Single> IBinaryNumber<Single> IBinaryNumber<TSelf> IBitwiseOperators<Single,Single,Single> IBitwiseOperators<TSelf,TSelf,TSelf> IComparisonOperators<Single,Single,Boolean> IComparisonOperators<TSelf,TSelf,Boolean> IDecrementOperators<Single> IDecrementOperators<TSelf> IDivisionOperators<Single,Single,Single> IDivisionOperators<TSelf,TSelf,TSelf> IEqualityOperators<Single,Single,Boolean> IEqualityOperators<TSelf,TOther,TResult> IEqualityOperators<TSelf,TSelf,Boolean> IExponentialFunctions<Single> IExponentialFunctions<TSelf> IFloatingPoint<Single> IFloatingPoint<TSelf> IFloatingPointConstants<Single> IFloatingPointConstants<TSelf> IFloatingPointIeee754<Single> IFloatingPointIeee754<TSelf> IHyperbolicFunctions<Single> IHyperbolicFunctions<TSelf> IIncrementOperators<Single> IIncrementOperators<TSelf> ILogarithmicFunctions<Single> ILogarithmicFunctions<TSelf> IMinMaxValue<Single> IModulusOperators<Single,Single,Single> IModulusOperators<TSelf,TSelf,TSelf> IMultiplicativeIdentity<Single,Single> IMultiplicativeIdentity<TSelf,TSelf> IMultiplyOperators<Single,Single,Single> IMultiplyOperators<TSelf,TSelf,TSelf> INumber<Single> INumber<TSelf> INumberBase<Single> INumberBase<TSelf> IPowerFunctions<Single> IPowerFunctions<TSelf> IRootFunctions<Single> IRootFunctions<TSelf> ISignedNumber<Single> ISignedNumber<TSelf> ISubtractionOperators<Single,Single,Single> ISubtractionOperators<TSelf,TSelf,TSelf> ITrigonometricFunctions<Single> ITrigonometricFunctions<TSelf> IUnaryNegationOperators<Single,Single> IUnaryNegationOperators<TSelf,TSelf> IUnaryPlusOperators<Single,Single> IUnaryPlusOperators<TSelf,TSelf> IUtf8SpanFormattable IUtf8SpanParsable<Single> IUtf8SpanParsable<TSelf>
注解
值 Single 类型表示一个单精度 32 位数字,其值范围为负 3.402823e38 到正 3.402823e38,以及正或负零、 PositiveInfinity、 NegativeInfinity和 ,而不是 () 的数字 NaN 。 它旨在表示极大 (的值,如行星或星系之间的距离) 或极小的 (如物质的分子质量(以公斤为单位) ),并且通常不精确 (如地球到另一个太阳系) 的距离。 该 Single 类型符合 IEC 60559:1989 (IEEE 754) 二进制浮点算术标准。
本文包含以下部分:
System.Single 提供了用于比较此类型的实例、将实例的值转换为其字符串表示形式以及将数字的字符串表示形式转换为此类型的实例的方法。 有关格式规范代码如何控制值类型的字符串表示形式的信息,请参阅 格式设置类型、 标准数字格式字符串和 自定义数值格式字符串。
浮点表示形式和精度
数据类型 Single 以 32 位二进制格式存储单精度浮点值,如下表所示:
组成部分 | Bits |
---|---|
有效或尾数 | 0-22 |
指数 | 23-30 |
符号 (0 = 正,1 = 负) | 31 |
正如小数分数无法精确表示某些小数值 ((如 1/3 或 Math.PI) )一样,二进制分数无法表示某些小数值。 例如,2/10 由 .2 精确表示为小数点,由 .0011111001001100 表示为二进制分数,模式“1100”重复为无穷大。 在这种情况下,浮点值提供它所表示的数字的不精确表示形式。 对原始浮点值执行其他数学运算通常会增加其精度不足。 例如,如果将 .3 乘以 10 的结果与 .3 相加 9 次的结果进行比较,则会看到该加法生成的结果精度较低,因为它涉及的运算比乘法多 8 个。 请注意,仅当使用“R”标准数字格式字符串显示这两Single个值时,这种差异才明显,如果需要,该字符串将显示类型支持Single的所有 9 位精度。
using System;
public class Example
{
public static void Main()
{
Single value = .2f;
Single result1 = value * 10f;
Single result2 = 0f;
for (int ctr = 1; ctr <= 10; ctr++)
result2 += value;
Console.WriteLine(".2 * 10: {0:R}", result1);
Console.WriteLine(".2 Added 10 times: {0:R}", result2);
}
}
// The example displays the following output:
// .2 * 10: 2
// .2 Added 10 times: 2.00000024
let value = 0.2f
let result1 = value * 10f
let mutable result2 = 0f
for _ = 1 to 10 do
result2 <- result2 + value
printfn $".2 * 10: {result1:R}"
printfn $".2 Added 10 times: {result2:R}"
// The example displays the following output:
// .2 * 10: 2
// .2 Added 10 times: 2.00000024
Module Example
Public Sub Main()
Dim value As Single = .2
Dim result1 As Single = value * 10
Dim result2 As Single
For ctr As Integer = 1 To 10
result2 += value
Next
Console.WriteLine(".2 * 10: {0:R}", result1)
Console.WriteLine(".2 Added 10 times: {0:R}", result2)
End Sub
End Module
' The example displays the following output:
' .2 * 10: 2
' .2 Added 10 times: 2.00000024
由于某些数字不能完全表示为小数二进制值,因此浮点数只能近似于实数。
所有浮点数都有有限数量的有效数字,这也决定了浮点值与实数近似的准确程度。 值 Single 最多具有 7 个十进制数字的精度,但内部最多保留 9 位。 这意味着某些浮点运算可能缺乏更改浮点值的精度。 以下示例定义一个大型单精度浮点值,然后将 的 Single.Epsilon 乘积和一个四千万亿。 但是,积太小,无法修改原始浮点值。 其最小有效数字为千分之一,而产品中最重要的数字为 10-30。
using System;
public class Example
{
public static void Main()
{
Single value = 123.456f;
Single additional = Single.Epsilon * 1e15f;
Console.WriteLine($"{value} + {additional} = {value + additional}");
}
}
// The example displays the following output:
// 123.456 + 1.401298E-30 = 123.456
open System
let value = 123.456f
let additional = Single.Epsilon * 1e15f
printfn $"{value} + {additional} = {value + additional}"
// The example displays the following output:
// 123.456 + 1.401298E-30 = 123.456
Module Example
Public Sub Main()
Dim value As Single = 123.456
Dim additional As Single = Single.Epsilon * 1e15
Console.WriteLine($"{value} + {additional} = {value + additional}")
End Sub
End Module
' The example displays the following output:
' 123.456 + 1.401298E-30 = 123.456
浮点数的有限精度有几个后果:
对于特定精度,看起来相等的两个浮点数在进行比较时可能不相等,因为其最小有效位不同。 在以下示例中,一系列数字相加,其总计与其预期总计进行比较。 尽管这两个值看起来是相同的,但对 方法的
Equals
调用指示它们不同。using System; public class Example { public static void Main() { Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f }; Single result = 27.65f; Single total = 0f; foreach (var value in values) total += value; if (total.Equals(result)) Console.WriteLine("The sum of the values equals the total."); else Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).", total, result); } } // The example displays the following output: // The sum of the values (27.65) does not equal the total (27.65). // // If the index items in the Console.WriteLine statement are changed to {0:R}, // the example displays the following output: // The sum of the values (27.6500015) does not equal the total (27.65).
let values = [| 10.01f; 2.88f; 2.88f; 2.88f; 9f |] let result = 27.65f let mutable total = 0f for value in values do total <- total + value if total.Equals result then printfn "The sum of the values equals the total." else printfn "The sum of the values ({total}) does not equal the total ({result})." // The example displays the following output: // The sum of the values (27.65) does not equal the total (27.65). // // If the index items in the Console.WriteLine statement are changed to {0:R}, // the example displays the following output: // The sum of the values (27.6500015) does not equal the total (27.65).
Module Example Public Sub Main() Dim values() As Single = { 10.01, 2.88, 2.88, 2.88, 9.0 } Dim result As Single = 27.65 Dim total As Single For Each value In values total += value Next If total.Equals(result) Then Console.WriteLine("The sum of the values equals the total.") Else Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).", total, result) End If End Sub End Module ' The example displays the following output: ' The sum of the values (27.65) does not equal the total (27.65). ' ' If the index items in the Console.WriteLine statement are changed to {0:R}, ' the example displays the following output: ' The sum of the values (27.639999999999997) does not equal the total (27.64).
如果将 语句中的 Console.WriteLine(String, Object, Object) 格式项从
{0}
和{1}
更改为{0:R}
,{1:R}
以显示两 Single 个值的所有有效数字,则很明显,这两个值不相等,因为在加法运算期间丢失精度。 在这种情况下,可以通过调用 Math.Round(Double, Int32) 方法将值舍入 Single 到所需的精度,然后再执行比较来解决该问题。如果使用十进制数,则使用浮点数的数学运算或比较运算可能不会产生相同的结果,因为二进制浮点数可能不等于十进制数。 前面的示例通过显示将 .3 乘以 10 并将 .3 乘以 9 次的结果来说明这一点。
当具有小数值的数值运算的准确性很重要时 Decimal ,请使用 类型而不是 Single 类型。 当整数值超出 或 UInt64 类型范围Int64的数字运算的准确性非常重要时,请使用 BigInteger 类型。
如果涉及浮点数,则值可能不会往返。 如果某个操作将原始浮点数转换为另一种形式,反运算将转换后的窗体转换回浮点数,而最终浮点数等于原始浮点数,则表示为往返值。 往返可能会失败,因为一个或多个有效数字在转换中丢失或更改。 在以下示例中,三 Single 个值将转换为字符串并保存在文件中。 如输出所示,尽管这些值看起来相同,但还原的值并不等于原始值。
using System; using System.IO; public class Example { public static void Main() { StreamWriter sw = new StreamWriter(@".\Singles.dat"); Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI }; for (int ctr = 0; ctr < values.Length; ctr++) { sw.Write(values[ctr].ToString()); if (ctr != values.Length - 1) sw.Write("|"); } sw.Close(); Single[] restoredValues = new Single[values.Length]; StreamReader sr = new StreamReader(@".\Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) restoredValues[ctr] = Single.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) Console.WriteLine("{0} {2} {1}", values[ctr], restoredValues[ctr], values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); } } // The example displays the following output: // 2.882883 <> 2.882883 // 0.3333333 <> 0.3333333 // 3.141593 <> 3.141593
open System open System.IO let values = [| 3.2f / 1.11f; 1f / 3f; MathF.PI |] do use sw = new StreamWriter(@".\Singles.dat") for i = 0 to values.Length - 1 do sw.Write(string values[i]) if i <> values.Length - 1 then sw.Write "|" let restoredValues = use sr = new StreamReader(@".\Singles.dat") sr.ReadToEnd().Split '|' |> Array.map Single.Parse for i = 0 to values.Length - 1 do printfn $"""{values[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}""" // The example displays the following output: // 2.882883 <> 2.882883 // 0.3333333 <> 0.3333333 // 3.141593 <> 3.141593
Imports System.IO Module Example Public Sub Main() Dim sw As New StreamWriter(".\Singles.dat") Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI) } For ctr As Integer = 0 To values.Length - 1 sw.Write(values(ctr).ToString()) If ctr <> values.Length - 1 Then sw.Write("|") Next sw.Close() Dim restoredValues(values.Length - 1) As Single Dim sr As New StreamReader(".\Singles.dat") Dim temp As String = sr.ReadToEnd() Dim tempStrings() As String = temp.Split("|"c) For ctr As Integer = 0 To tempStrings.Length - 1 restoredValues(ctr) = Single.Parse(tempStrings(ctr)) Next For ctr As Integer = 0 To values.Length - 1 Console.WriteLine("{0} {2} {1}", values(ctr), restoredValues(ctr), If(values(ctr).Equals(restoredValues(ctr)), "=", "<>")) Next End Sub End Module ' The example displays the following output: ' 2.882883 <> 2.882883 ' 0.3333333 <> 0.3333333 ' 3.141593 <> 3.141593
在这种情况下,通过使用“G9” 标准数字格式字符串 来保留值的完整精度 Single ,可以成功地对值进行舍入,如以下示例所示。
using System; using System.IO; public class Example { public static void Main() { StreamWriter sw = new StreamWriter(@".\Singles.dat"); Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI }; for (int ctr = 0; ctr < values.Length; ctr++) sw.Write("{0:G9}{1}", values[ctr], ctr < values.Length - 1 ? "|" : "" ); sw.Close(); Single[] restoredValues = new Single[values.Length]; StreamReader sr = new StreamReader(@".\Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) restoredValues[ctr] = Single.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) Console.WriteLine("{0} {2} {1}", values[ctr], restoredValues[ctr], values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); } } // The example displays the following output: // 2.882883 = 2.882883 // 0.3333333 = 0.3333333 // 3.141593 = 3.141593
open System open System.IO let values = [| 3.2f / 1.11f; 1f / 3f; MathF.PI |] do use sw = new StreamWriter(@".\Singles.dat") for i = 0 to values.Length - 1 do sw.Write $"""{values[i]:G9}{if i < values.Length - 1 then "|" else ""}""" let restoredValues = use sr = new StreamReader(@".\Singles.dat") sr.ReadToEnd().Split '|' |> Array.map Single.Parse for i = 0 to values.Length - 1 do printfn $"""{values[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}""" // The example displays the following output: // 2.882883 = 2.882883 // 0.3333333 = 0.3333333 // 3.141593 = 3.141593
Imports System.IO Module Example Public Sub Main() Dim sw As New StreamWriter(".\Singles.dat") Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI) } For ctr As Integer = 0 To values.Length - 1 sw.Write("{0:G9}{1}", values(ctr), If(ctr < values.Length - 1, "|", "")) Next sw.Close() Dim restoredValues(values.Length - 1) As Single Dim sr As New StreamReader(".\Singles.dat") Dim temp As String = sr.ReadToEnd() Dim tempStrings() As String = temp.Split("|"c) For ctr As Integer = 0 To tempStrings.Length - 1 restoredValues(ctr) = Single.Parse(tempStrings(ctr)) Next For ctr As Integer = 0 To values.Length - 1 Console.WriteLine("{0} {2} {1}", values(ctr), restoredValues(ctr), If(values(ctr).Equals(restoredValues(ctr)), "=", "<>")) Next End Sub End Module ' The example displays the following output: ' 2.882883 = 2.882883 ' 0.3333333 = 0.3333333 ' 3.141593 = 3.141593
Single 值的精度低于 Double 值。 Single由于精度差异,转换为看似等效Double的值通常不等于Double值。 在以下示例中,将相同的除法运算的结果赋给 值 Double 和 Single 值。 将 Single 值强制转换为 后,两个 Double值的比较表明它们不相等。
using System; public class Example { public static void Main() { Double value1 = 1/3.0; Single sValue2 = 1/3.0f; Double value2 = (Double) sValue2; Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); } } // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
open System let value1 = 1. / 3. let sValue2 = 1f /3f let value2 = double sValue2 printfn $"{value1:R} = {value2:R}: {value1.Equals value2}" // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
Module Example Public Sub Main() Dim value1 As Double = 1/3 Dim sValue2 As Single = 1/3 Dim value2 As Double = CDbl(sValue2) Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2)) End Sub End Module ' The example displays the following output: ' 0.33333333333333331 = 0.3333333432674408: False
若要避免此问题,请使用 Double 数据类型代替 Single 数据类型,或使用 Round 方法使两个值具有相同的精度。
测试相等性
若要被视为相等,两个 Single 值必须表示相同的值。 但是,由于值之间的精度差异,或者由于一个或两个值丢失精度,预期相同的浮点值通常由于最小有效位数的差异而变得不相等。 因此,调用 Equals 方法以确定两个值是否相等,或调用 CompareTo 方法以确定两个 Single 值之间的关系,通常会产生意外的结果。 这在下面的示例中很明显,其中两个明显相等 Single 的值结果不相等,因为第一个值的精度为 7 位,而第二个值具有 9 位。
using System;
public class Example
{
public static void Main()
{
float value1 = .3333333f;
float value2 = 1.0f/3;
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
}
}
// The example displays the following output:
// 0.3333333 = 0.333333343: False
let value1 = 0.3333333f
let value2 = 1f / 3f
printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
// The example displays the following output:
// 0.3333333 = 0.333333343: False
Module Example
Public Sub Main()
Dim value1 As Single = .3333333
Dim value2 As Single = 1/3
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
End Sub
End Module
' The example displays the following output:
' 0.3333333 = 0.333333343: False
遵循不同代码路径且以不同方式操作的计算值通常被证明是不相等的。 在以下示例中,一个 Single 值为平方,然后计算平方根以还原原始值。 秒 Single 乘以 3.51,在结果的平方根除以 3.51 之前平方,以还原原始值。 尽管这两个值看起来相同,但对 方法的 Equals(Single) 调用指示它们不相等。 使用“G9”标准格式字符串返回显示每个 Single 值的所有有效数字的结果字符串显示第二个值比第一个值小 .0000000000001。
using System;
public class Example
{
public static void Main()
{
float value1 = 10.201438f;
value1 = (float) Math.Sqrt((float) Math.Pow(value1, 2));
float value2 = (float) Math.Pow((float) value1 * 3.51f, 2);
value2 = ((float) Math.Sqrt(value2)) / 3.51f;
Console.WriteLine("{0} = {1}: {2}\n",
value1, value2, value1.Equals(value2));
Console.WriteLine("{0:G9} = {1:G9}", value1, value2);
}
}
// The example displays the following output:
// 10.20144 = 10.20144: False
//
// 10.201438 = 10.2014389
let value1 =
10.201438f ** 2f
|> sqrt
let value2 =
((value1 * 3.51f) ** 2f |> sqrt) / 3.51f
printfn $"{value1} = {value2}: {value1.Equals value2}\n"
printfn $"{value1:G9} = {value2:G9}"
// The example displays the following output:
// 10.20144 = 10.20144: False
//
// 10.201438 = 10.2014389
Module Example
Public Sub Main()
Dim value1 As Single = 10.201438
value1 = CSng(Math.Sqrt(CSng(Math.Pow(value1, 2))))
Dim value2 As Single = CSng(Math.Pow(value1 * CSng(3.51), 2))
value2 = CSng(Math.Sqrt(value2) / CSng(3.51))
Console.WriteLine("{0} = {1}: {2}",
value1, value2, value1.Equals(value2))
Console.WriteLine()
Console.WriteLine("{0:G9} = {1:G9}", value1, value2)
End Sub
End Module
' The example displays the following output:
' 10.20144 = 10.20144: False
'
' 10.201438 = 10.2014389
在精度损失可能会影响比较结果的情况下,可以使用以下技术,而不是调用 Equals 或 CompareTo 方法:
Math.Round调用 方法以确保这两个值具有相同的精度。 下面的示例修改前面的示例以使用此方法,使两个小数部分值等效。
using System; public class Example { public static void Main() { float value1 = .3333333f; float value2 = 1.0f/3; int precision = 7; value1 = (float) Math.Round(value1, precision); value2 = (float) Math.Round(value2, precision); Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); } } // The example displays the following output: // 0.3333333 = 0.3333333: True
open System let value1 = 0.3333333f let value2 = 1f / 3f let precision = 7 let value1r = Math.Round(float value1, precision) |> float32 let value2r = Math.Round(float value2, precision) |> float32 printfn $"{value1:R} = {value2:R}: {value1.Equals value2}" // The example displays the following output: // 0.3333333 = 0.3333333: True
Module Example Public Sub Main() Dim value1 As Single = .3333333 Dim value2 As Single = 1/3 Dim precision As Integer = 7 value1 = CSng(Math.Round(value1, precision)) value2 = CSng(Math.Round(value2, precision)) Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)) End Sub End Module ' The example displays the following output: ' 0.3333333 = 0.3333333: True
精度问题仍适用于中点值的舍入。 有关更多信息,请参见 Math.Round(Double, Int32, MidpointRounding) 方法。
测试近似相等性而不是相等性。 此方法要求定义两个值可以相差但仍相等的绝对量,或者定义较小的值与较大值相差的相对量。
警告
Single.Epsilon 在测试相等性时,有时用作两 Single 个值之间距离的绝对度量值。 但是, Single.Epsilon 测量可以添加到 的或从中减去的最小可能值, Single 其值为零。 对于大多数正值和负 Single 值,的值 Single.Epsilon 太小,无法检测到。 因此,除零值外,我们不建议在相等性测试中使用它。
以下示例使用后一种方法来定义测试两个
IsApproximatelyEqual
值之间的相对差异的方法。 它还对调用IsApproximatelyEqual
方法和 方法 Equals(Single) 的结果进行对比。using System; public class Example { public static void Main() { float one1 = .1f * 10; float one2 = 0f; for (int ctr = 1; ctr <= 10; ctr++) one2 += .1f; Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2)); Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", one1, one2, IsApproximatelyEqual(one1, one2, .000001f)); } static bool IsApproximatelyEqual(float value1, float value2, float epsilon) { // If they are equal anyway, just return True. if (value1.Equals(value2)) return true; // Handle NaN, Infinity. if (Double.IsInfinity(value1) | Double.IsNaN(value1)) return value1.Equals(value2); else if (Double.IsInfinity(value2) | Double.IsNaN(value2)) return value1.Equals(value2); // Handle zero to avoid division by zero double divisor = Math.Max(value1, value2); if (divisor.Equals(0)) divisor = Math.Min(value1, value2); return Math.Abs(value1 - value2)/divisor <= epsilon; } } // The example displays the following output: // 1 = 1.00000012: False // 1 is approximately equal to 1.00000012: True
open System let isApproximatelyEqual value1 value2 epsilon = // If they are equal anyway, just return True. if value1.Equals value2 then true // Handle NaN, Infinity. elif Single.IsInfinity value1 || Single.IsNaN value1 then value1.Equals value2 elif Single.IsInfinity value2 || Single.IsNaN value2 then value1.Equals value2 else // Handle zero to avoid division by zero let divisor = max value1 value2 let divisor = if divisor.Equals 0 then min value1 value2 else divisor abs (value1 - value2) / divisor <= epsilon let one1 = 0.1f * 10f let mutable one2 = 0f for _ = 1 to 10 do one2 <- one2 + 0.1f printfn $"{one1:R} = {one2:R}: {one1.Equals one2}" printfn $"{one1:R} is approximately equal to {one2:R}: {isApproximatelyEqual one1 one2 0.000001f}" // The example displays the following output: // 1 = 1.00000012: False // 1 is approximately equal to 1.00000012: True
Module Example Public Sub Main() Dim one1 As Single = .1 * 10 Dim one2 As Single = 0 For ctr As Integer = 1 To 10 one2 += CSng(.1) Next Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2)) Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", one1, one2, IsApproximatelyEqual(one1, one2, .000001)) End Sub Function IsApproximatelyEqual(value1 As Single, value2 As Single, epsilon As Single) As Boolean ' If they are equal anyway, just return True. If value1.Equals(value2) Then Return True ' Handle NaN, Infinity. If Single.IsInfinity(value1) Or Single.IsNaN(value1) Then Return value1.Equals(value2) Else If Single.IsInfinity(value2) Or Single.IsNaN(value2) Return value1.Equals(value2) End If ' Handle zero to avoid division by zero Dim divisor As Single = Math.Max(value1, value2) If divisor.Equals(0) Then divisor = Math.Min(value1, value2) End If Return Math.Abs(value1 - value2)/divisor <= epsilon End Function End Module ' The example displays the following output: ' 1 = 1.00000012: False ' 1 is approximately equal to 1.00000012: True
浮点值和异常
具有浮点值的操作不会引发异常,这与具有整型类型的操作不同,后者在非法操作(如被零除或溢出)时引发异常。 相反,在这些情况下,浮点运算的结果为零、正无穷大、负无穷大或非数字 (NaN) :
如果浮点运算的结果对于目标格式来说太小,则结果为零。 当两个非常小的浮点数相乘时,可能会发生这种情况,如以下示例所示。
using System; public class Example { public static void Main() { float value1 = 1.163287e-36f; float value2 = 9.164234e-25f; float result = value1 * value2; Console.WriteLine("{0} * {1} = {2}", value1, value2, result); Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0f)); } } // The example displays the following output: // 1.163287E-36 * 9.164234E-25 = 0 // 0 = 0: True
let value1 = 1.163287e-36f let value2 = 9.164234e-25f let result = value1 * value2 printfn $"{value1} * {value2} = {result}" printfn $"{result} = 0: {result.Equals(0f)}" // The example displays the following output: // 1.163287E-36 * 9.164234E-25 = 0 // 0 = 0: True
Module Example Public Sub Main() Dim value1 As Single = 1.163287e-36 Dim value2 As Single = 9.164234e-25 Dim result As Single = value1 * value2 Console.WriteLine("{0} * {1} = {2:R}", value1, value2, result) Console.WriteLine("{0} = 0: {1}", result, result.Equals(0)) End Sub End Module ' The example displays the following output: ' 1.163287E-36 * 9.164234E-25 = 0 ' 0 = 0: True
如果浮点运算结果的大小超过目标格式的范围,则运算的结果为 PositiveInfinity 或 NegativeInfinity,具体取决于结果的符号。 溢出 Single.MaxValue 操作的结果为 PositiveInfinity,溢出 Single.MinValue 操作的结果为 NegativeInfinity,如以下示例所示。
using System; public class Example { public static void Main() { float value1 = 3.065e35f; float value2 = 6.9375e32f; float result = value1 * value2; Console.WriteLine("PositiveInfinity: {0}", Single.IsPositiveInfinity(result)); Console.WriteLine("NegativeInfinity: {0}\n", Single.IsNegativeInfinity(result)); value1 = -value1; result = value1 * value2; Console.WriteLine("PositiveInfinity: {0}", Single.IsPositiveInfinity(result)); Console.WriteLine("NegativeInfinity: {0}", Single.IsNegativeInfinity(result)); } } // The example displays the following output: // PositiveInfinity: True // NegativeInfinity: False // // PositiveInfinity: False // NegativeInfinity: True
open System let value1 = 3.065e35f let value2 = 6.9375e32f let result = value1 * value2 printfn $"PositiveInfinity: {Single.IsPositiveInfinity result}" printfn $"NegativeInfinity: {Single.IsNegativeInfinity result}\n" let value3 = -value1 let result2 = value3 * value2 printfn $"PositiveInfinity: {Single.IsPositiveInfinity result}" printfn $"NegativeInfinity: {Single.IsNegativeInfinity result}" // The example displays the following output: // PositiveInfinity: True // NegativeInfinity: False // // PositiveInfinity: False // NegativeInfinity: True
Module Example Public Sub Main() Dim value1 As Single = 3.065e35 Dim value2 As Single = 6.9375e32 Dim result As Single = value1 * value2 Console.WriteLine("PositiveInfinity: {0}", Single.IsPositiveInfinity(result)) Console.WriteLine("NegativeInfinity: {0}", Single.IsNegativeInfinity(result)) Console.WriteLine() value1 = -value1 result = value1 * value2 Console.WriteLine("PositiveInfinity: {0}", Single.IsPositiveInfinity(result)) Console.WriteLine("NegativeInfinity: {0}", Single.IsNegativeInfinity(result)) End Sub End Module ' The example displays the following output: ' PositiveInfinity: True ' NegativeInfinity: False ' ' PositiveInfinity: False ' NegativeInfinity: True
PositiveInfinity 此外,除数为 0 且股息为正, NegativeInfinity 而除数为零且股息为负的结果。
如果浮点运算无效,则该操作的结果为 NaN。 例如, NaN 以下操作的结果:
除以零,股息为零。 请注意,除以零的其他情况会导致 PositiveInfinity 或 NegativeInfinity。
具有无效输入的任何浮点操作。 例如,尝试查找负值的平方根将 NaN返回 。
具有其值为 Single.NaN的参数的任何操作。
类型转换和单一结构
结构 Single 不定义任何显式或隐式转换运算符;相反,转换由编译器实现。
下表列出了其他基元数值类型的值可能转换为值 Single ,它还指示转换是扩大还是缩小,以及生成的 Single 精度是否低于原始值。
从 | 扩大/缩小 | 可能的精度损失 |
---|---|---|
Byte | Widening | 否 |
Decimal | Widening 请注意,C# 需要强制转换运算符。 |
是的。 Decimal 支持 29 个十进制数字的精度; Single 支持 9。 |
Double | 缩小;范围外值将 Double.NegativeInfinity 转换为 或 Double.PositiveInfinity。 | 是的。 Double 支持 17 个十进制精度位; Single 支持 9。 |
Int16 | Widening | 否 |
Int32 | Widening | 是的。 Int32 支持 10 个十进制精度位; Single 支持 9。 |
Int64 | Widening | 是的。 Int64 支持 19 个精度的十进制数字; Single 支持 9。 |
SByte | Widening | 否 |
UInt16 | Widening | 否 |
UInt32 | Widening | 是的。 UInt32 支持 10 个十进制精度位; Single 支持 9。 |
UInt64 | Widening | 是的。 Int64 支持 20 个十进制数字的精度; Single 支持 9。 |
以下示例将其他基元数值类型的最小值或最大值转换为 Single 值。
using System;
public class Example
{
public static void Main()
{
dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
Decimal.MaxValue, Double.MinValue, Double.MaxValue,
Int16.MinValue, Int16.MaxValue, Int32.MinValue,
Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
UInt64.MinValue, UInt64.MaxValue };
float sngValue;
foreach (var value in values) {
if (value.GetType() == typeof(Decimal) ||
value.GetType() == typeof(Double))
sngValue = (float) value;
else
sngValue = value;
Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
value, value.GetType().Name,
sngValue, sngValue.GetType().Name);
}
}
}
// The example displays the following output:
// 0 (Byte) --> 0 (Single)
// 255 (Byte) --> 255 (Single)
// -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
// 79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
// -1.79769313486232E+308 (Double) --> -Infinity (Single)
// 1.79769313486232E+308 (Double) --> Infinity (Single)
// -32768 (Int16) --> -32768 (Single)
// 32767 (Int16) --> 32767 (Single)
// -2147483648 (Int32) --> -2.14748365E+09 (Single)
// 2147483647 (Int32) --> 2.14748365E+09 (Single)
// -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
// 9223372036854775807 (Int64) --> 9.223372E+18 (Single)
// -128 (SByte) --> -128 (Single)
// 127 (SByte) --> 127 (Single)
// 0 (UInt16) --> 0 (Single)
// 65535 (UInt16) --> 65535 (Single)
// 0 (UInt32) --> 0 (Single)
// 4294967295 (UInt32) --> 4.2949673E+09 (Single)
// 0 (UInt64) --> 0 (Single)
// 18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
open System
let values: obj list =
[ Byte.MinValue; Byte.MaxValue; Decimal.MinValue
Decimal.MaxValue; Double.MinValue; Double.MaxValue
Int16.MinValue; Int16.MaxValue; Int32.MinValue
Int32.MaxValue; Int64.MinValue; Int64.MaxValue
SByte.MinValue; SByte.MaxValue; UInt16.MinValue
UInt16.MaxValue; UInt32.MinValue; UInt32.MaxValue
UInt64.MinValue; UInt64.MaxValue ]
for value in values do
let sngValue =
match value with
| :? byte as v -> float32 v
| :? decimal as v -> float32 v
| :? double as v -> float32 v
| :? int16 as v -> float32 v
| :? int as v -> float32 v
| :? int64 as v -> float32 v
| :? int8 as v -> float32 v
| :? uint16 as v -> float32 v
| :? uint as v -> float32 v
| :? uint64 as v -> float32 v
| _ -> raise (NotImplementedException "Unknown Type")
printfn $"{value} ({value.GetType().Name}) --> {sngValue:R} ({sngValue.GetType().Name})"
// The example displays the following output:
// 0 (Byte) --> 0 (Single)
// 255 (Byte) --> 255 (Single)
// -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
// 79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
// -1.79769313486232E+308 (Double) --> -Infinity (Single)
// 1.79769313486232E+308 (Double) --> Infinity (Single)
// -32768 (Int16) --> -32768 (Single)
// 32767 (Int16) --> 32767 (Single)
// -2147483648 (Int32) --> -2.14748365E+09 (Single)
// 2147483647 (Int32) --> 2.14748365E+09 (Single)
// -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
// 9223372036854775807 (Int64) --> 9.223372E+18 (Single)
// -128 (SByte) --> -128 (Single)
// 127 (SByte) --> 127 (Single)
// 0 (UInt16) --> 0 (Single)
// 65535 (UInt16) --> 65535 (Single)
// 0 (UInt32) --> 0 (Single)
// 4294967295 (UInt32) --> 4.2949673E+09 (Single)
// 0 (UInt64) --> 0 (Single)
// 18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
Module Example
Public Sub Main()
Dim values() As Object = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
Decimal.MaxValue, Double.MinValue, Double.MaxValue,
Int16.MinValue, Int16.MaxValue, Int32.MinValue,
Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
UInt64.MinValue, UInt64.MaxValue }
Dim sngValue As Single
For Each value In values
If value.GetType() = GetType(Double) Then
sngValue = CSng(value)
Else
sngValue = value
End If
Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
value, value.GetType().Name,
sngValue, sngValue.GetType().Name)
Next
End Sub
End Module
' The example displays the following output:
' 0 (Byte) --> 0 (Single)
' 255 (Byte) --> 255 (Single)
' -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
' 79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
' -1.79769313486232E+308 (Double) --> -Infinity (Single)
' 1.79769313486232E+308 (Double) --> Infinity (Single)
' -32768 (Int16) --> -32768 (Single)
' 32767 (Int16) --> 32767 (Single)
' -2147483648 (Int32) --> -2.14748365E+09 (Single)
' 2147483647 (Int32) --> 2.14748365E+09 (Single)
' -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
' 9223372036854775807 (Int64) --> 9.223372E+18 (Single)
' -128 (SByte) --> -128 (Single)
' 127 (SByte) --> 127 (Single)
' 0 (UInt16) --> 0 (Single)
' 65535 (UInt16) --> 65535 (Single)
' 0 (UInt32) --> 0 (Single)
' 4294967295 (UInt32) --> 4.2949673E+09 (Single)
' 0 (UInt64) --> 0 (Single)
' 18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
此外, Double 值 Double.NaN、 Double.PositiveInfinity和 Double.NegativeInfinity 分别转换为 Single.NaN、 Single.PositiveInfinity和 Single.NegativeInfinity。
请注意,某些数值类型的值转换为 Single 值可能会导致精度损失。 如示例所示,将 、、、Int64Int32DoubleUInt32、 和 UInt64 值转换为Decimal值Single时,可能会丢失精度。
值到 Double 的转换Single是一种扩大的转换。 如果类型没有值的精确表示形式Single,Double则转换可能会导致精度损失。
将值转换为 Single 除 以外的 Double 任何基元数值数据类型的值都是一种收缩转换,需要 C#) 中的强制转换运算符 (,或者在 Visual Basic) 中 (转换方法。 目标数据类型范围之外的值(由目标类型的 MinValue
和 MaxValue
属性定义)的行为如下表所示。
目标类型 | 结果 |
---|---|
任何整型类型 | OverflowException如果转换发生在选中的上下文中,则为异常。 如果转换发生在未选中的上下文中, (C#) 中的默认值,则转换操作会成功,但值溢出。 |
Decimal | 异常 OverflowException , |
此外, Single.NaN、 Single.PositiveInfinity和 Single.NegativeInfinity 引发 , OverflowException 用于在选中的上下文中转换为整数,但这些值在未选中的上下文中转换为整数时会溢出。 对于 转换为 Decimal,它们始终引发 OverflowException。 对于 转换为 Double,它们分别转换为 Double.NaN、 Double.PositiveInfinity和 Double.NegativeInfinity。
请注意,将值转换为另一个 Single 数值类型可能会导致精度损失。 在转换非整型 Single 值的情况下,如示例输出所示,当值在 Visual Basic) 中舍入 (或截断 ((如 C# 和 F#) 中所示)时 Single ,小数部分将丢失。 对于值 Decimal 转换, Single 该值在目标数据类型中可能没有精确的表示形式。
以下示例将多个 Single 值转换为其他几个数值类型。 转换发生在 Visual Basic (默认) 的选中上下文中,在 C# (中由于选中的关键字 (keyword) ) ,在 F# (中由于open Checked
语句) 。 该示例的输出显示了两个选中的未选中上下文中的转换结果。 可以在 Visual Basic 中的未选中上下文中执行转换,方法是使用 /removeintchecks+
编译器开关进行编译;在 C# 中通过注释掉 checked
语句;在 F# 中通过注释掉 open Checked
语句来执行转换。
using System;
public class Example
{
public static void Main()
{
float[] values = { Single.MinValue, -67890.1234f, -12345.6789f,
12345.6789f, 67890.1234f, Single.MaxValue,
Single.NaN, Single.PositiveInfinity,
Single.NegativeInfinity };
checked {
foreach (var value in values) {
try {
Int64 lValue = (long) value;
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
lValue, lValue.GetType().Name);
}
catch (OverflowException) {
Console.WriteLine("Unable to convert {0} to Int64.", value);
}
try {
UInt64 ulValue = (ulong) value;
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
ulValue, ulValue.GetType().Name);
}
catch (OverflowException) {
Console.WriteLine("Unable to convert {0} to UInt64.", value);
}
try {
Decimal dValue = (decimal) value;
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dValue, dValue.GetType().Name);
}
catch (OverflowException) {
Console.WriteLine("Unable to convert {0} to Decimal.", value);
}
Double dblValue = value;
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dblValue, dblValue.GetType().Name);
Console.WriteLine();
}
}
}
}
// The example displays the following output for conversions performed
// in a checked context:
// Unable to convert -3.402823E+38 to Int64.
// Unable to convert -3.402823E+38 to UInt64.
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// Unable to convert -67890.13 to UInt64.
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// Unable to convert -12345.68 to UInt64.
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// Unable to convert 3.402823E+38 to Int64.
// Unable to convert 3.402823E+38 to UInt64.
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// Unable to convert NaN to Int64.
// Unable to convert NaN to UInt64.
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Unable to convert Infinity to Int64.
// Unable to convert Infinity to UInt64.
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// Unable to convert -Infinity to Int64.
// Unable to convert -Infinity to UInt64.
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
// -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// 3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// 3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// NaN (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
open System
open Checked
let values =
[ Single.MinValue; -67890.1234f; -12345.6789f
12345.6789f; 67890.1234f; Single.MaxValue
Single.NaN; Single.PositiveInfinity
Single.NegativeInfinity ]
for value in values do
try
let lValue = int64 value
printfn $"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"
with :? OverflowException ->
printfn $"Unable to convert {value} to Int64."
try
let ulValue = uint64 value
printfn $"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"
with :? OverflowException ->
printfn $"Unable to convert {value} to UInt64."
try
let dValue = decimal value
printfn $"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"
with :? OverflowException ->
printfn $"Unable to convert {value} to Decimal."
let dblValue = double value
printfn $"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})\n"
// The example displays the following output for conversions performed
// in a checked context:
// Unable to convert -3.402823E+38 to Int64.
// Unable to convert -3.402823E+38 to UInt64.
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// Unable to convert -67890.13 to UInt64.
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// Unable to convert -12345.68 to UInt64.
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// Unable to convert 3.402823E+38 to Int64.
// Unable to convert 3.402823E+38 to UInt64.
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// Unable to convert NaN to Int64.
// Unable to convert NaN to UInt64.
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Unable to convert Infinity to Int64.
// Unable to convert Infinity to UInt64.
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// Unable to convert -Infinity to Int64.
// Unable to convert -Infinity to UInt64.
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
// -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// 3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// 3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// NaN (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
Module Example
Public Sub Main()
Dim values() As Single = { Single.MinValue, -67890.1234, -12345.6789,
12345.6789, 67890.1234, Single.MaxValue,
Single.NaN, Single.PositiveInfinity,
Single.NegativeInfinity }
For Each value In values
Try
Dim lValue As Long = CLng(value)
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
lValue, lValue.GetType().Name)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to Int64.", value)
End Try
Try
Dim ulValue As UInt64 = CULng(value)
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
ulValue, ulValue.GetType().Name)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to UInt64.", value)
End Try
Try
Dim dValue As Decimal = CDec(value)
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dValue, dValue.GetType().Name)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to Decimal.", value)
End Try
Dim dblValue As Double = value
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dblValue, dblValue.GetType().Name)
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output for conversions performed
' in a checked context:
' Unable to convert -3.402823E+38 to Int64.
' Unable to convert -3.402823E+38 to UInt64.
' Unable to convert -3.402823E+38 to Decimal.
' -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
' -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
' Unable to convert -67890.13 to UInt64.
' -67890.13 (Single) --> -67890.12 (Decimal)
' -67890.13 (Single) --> -67890.125 (Double)
'
' -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
' Unable to convert -12345.68 to UInt64.
' -12345.68 (Single) --> -12345.68 (Decimal)
' -12345.68 (Single) --> -12345.6787109375 (Double)
'
' 12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
' 12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
' 12345.68 (Single) --> 12345.68 (Decimal)
' 12345.68 (Single) --> 12345.6787109375 (Double)
'
' 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
' 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
' 67890.13 (Single) --> 67890.12 (Decimal)
' 67890.13 (Single) --> 67890.125 (Double)
'
' Unable to convert 3.402823E+38 to Int64.
' Unable to convert 3.402823E+38 to UInt64.
' Unable to convert 3.402823E+38 to Decimal.
' 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
' Unable to convert NaN to Int64.
' Unable to convert NaN to UInt64.
' Unable to convert NaN to Decimal.
' NaN (Single) --> NaN (Double)
'
' Unable to convert Infinity to Int64.
' Unable to convert Infinity to UInt64.
' Unable to convert Infinity to Decimal.
' Infinity (Single) --> Infinity (Double)
'
' Unable to convert -Infinity to Int64.
' Unable to convert -Infinity to UInt64.
' Unable to convert -Infinity to Decimal.
' -Infinity (Single) --> -Infinity (Double)
' The example displays the following output for conversions performed
' in an unchecked context:
' -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
' Unable to convert -3.402823E+38 to Decimal.
' -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
' -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
' -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
' -67890.13 (Single) --> -67890.12 (Decimal)
' -67890.13 (Single) --> -67890.125 (Double)
'
' -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
' -12345.68 (Single) --> 18446744073709539270 (0xFFFFFFFFFFFFCFC6) (UInt64)
' -12345.68 (Single) --> -12345.68 (Decimal)
' -12345.68 (Single) --> -12345.6787109375 (Double)
'
' 12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
' 12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
' 12345.68 (Single) --> 12345.68 (Decimal)
' 12345.68 (Single) --> 12345.6787109375 (Double)
'
' 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
' 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
' 67890.13 (Single) --> 67890.12 (Decimal)
' 67890.13 (Single) --> 67890.125 (Double)
'
' 3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' 3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
' Unable to convert 3.402823E+38 to Decimal.
' 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
' NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' NaN (Single) --> 0 (0x0000000000000000) (UInt64)
' Unable to convert NaN to Decimal.
' NaN (Single) --> NaN (Double)
'
' Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
' Unable to convert Infinity to Decimal.
' Infinity (Single) --> Infinity (Double)
'
' -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
' Unable to convert -Infinity to Decimal.
' -Infinity (Single) --> -Infinity (Double)
有关数值类型转换的详细信息,请参阅.NET Framework和类型转换表中的类型转换。
浮点功能
结构 Single 和相关类型提供用于执行以下类别操作的方法:
值的比较。 可以调用 方法来确定两个Single值是否相等,也可以CompareTo调用 Equals 方法来确定两个值之间的关系。
结构 Single 还支持一组完整的比较运算符。 例如,可以测试相等性或不等性,或者确定一个值是否大于或等于另一个值。 如果其中一个操作数是 , Double则会在执行比较之前将 Single 值转换为 Double 。 如果其中一个操作数是整型类型,则会在执行比较之前将其转换为 Single 。 尽管这些转换正在扩大,但它们可能涉及精度损失。
还可以调用 IsNaN、 IsInfinity、 IsPositiveInfinity和 IsNegativeInfinity 方法来测试这些特殊值。
数学运算。 常见的算术运算(如加法、减法、乘法和除法)由语言编译器和通用中间语言 (CIL) 指令而不是方法 Single 实现。 如果数学运算中的另一个 Double操作数是 ,则会 Single 在执行运算之前转换为 , Double 并且运算的结果也是一个 Double 值。 如果另一个操作数是整型类型,则在执行操作之前将其转换为 Single ,并且操作的结果也是一个 Single 值。
可以通过调用
static
类中的 Visual Basic) 方法System.Math中的 (Shared
来执行其他数学运算。 其中包括常用于算术 ((如 Math.Abs、 Math.Sign和 Math.Sqrt) )的其他方法、几何 ((如 Math.Cos 和 Math.Sin) )和微积分 ((如 Math.Log) )。 在所有情况下, Single 值都转换为 Double。还可以操作值中的 Single 单个位。 方法 BitConverter.GetBytes(Single) 在字节数组中返回其位模式。 通过将该字节数组传递给 BitConverter.ToInt32 方法,还可以将值的位模式保留 Single 为 32 位整数。
舍入。 舍入通常用作一种技术,用于减少浮点表示和精度问题引起的值之间的差异的影响。 可以通过调用 Math.Round 方法对Single值进行舍入。 但请注意,在 Single 调用 方法之前,值会 Double 转换为 ,并且转换可能涉及精度损失。
格式设置。 可以通过调用 ToString 方法或使用复合格式设置功能将值转换为Single其字符串表示形式。 有关格式字符串如何控制浮点值的字符串表示形式的信息,请参阅 标准数字格式字符串 和 自定义数值格式字符串 主题。
分析字符串。 可以通过调用 Parse 或 TryParse 方法将浮点值的字符串表示形式转换为Single值。 如果分析操作失败,该方法 Parse 将引发异常,而 TryParse 该方法返回
false
。类型转换。 结构Single为 IConvertible 接口提供显式接口实现,该接口支持在任意两个标准.NET Framework数据类型之间进行转换。 语言编译器还支持所有其他标准数值类型的值隐式转换DoubleSingle,但 转换为值除外。 将除 以外的 Double 任何标准数值类型的值转换为 都是 Single 一种扩大的转换,不需要使用强制转换运算符或转换方法。
但是,32 位和 64 位整数值的转换可能会造成精度损失。 下表列出了 32 位、64 位和 Double 类型的精度差异:
类型 以十进制数字) 的最大精度 ( 内部精度 (十进制数字) Double 15 17 Int32 和 UInt32 10 10 Int64 和 UInt64 19 19 Single 7 9 精度问题最常影响 Single 转换为 Double 值的值。 在以下示例中,由相同除法运算生成的两个 Double值是不相等的,因为其中一个值是转换为 的单精度浮点值。
using System; public class Example { public static void Main() { Double value1 = 1/3.0; Single sValue2 = 1/3.0f; Double value2 = (Double) sValue2; Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); } } // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
let value1 = 1. / 3. let sValue2 = 1f / 3f let value2 = double sValue2 printfn $"{value1:R} = {value2:R}: {value1.Equals value2}" // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
Module Example Public Sub Main() Dim value1 As Double = 1/3 Dim sValue2 As Single = 1/3 Dim value2 As Double = CDbl(sValue2) Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2)) End Sub End Module ' The example displays the following output: ' 0.33333333333333331 = 0.3333333432674408: False
字段
E |
表示由常量 e 指定的自然对数底。 |
Epsilon |
表示大于零的最小正 Single 值。 此字段为常数。 |
MaxValue |
表示 Single 的最大可能值。 此字段为常数。 |
MinValue |
表示 Single 的最小可能值。 此字段为常数。 |
NaN |
表示非数字 ( |
NegativeInfinity |
表示负无穷。 此字段为常数。 |
NegativeZero |
表示数字负零 (-0) 。 |
Pi |
表示圆的周长与其直径的比值,由常数 π 指定。 |
PositiveInfinity |
表示正无穷。 此字段为常数。 |
Tau |
表示一转中的弧度数,由常量 τ 指定。 |
方法
运算符
Equality(Single, Single) |
返回一个值,该值指示两个指定的 Single 值是否相等。 |
GreaterThan(Single, Single) | |
GreaterThanOrEqual(Single, Single) | |
Inequality(Single, Single) |
返回一个值,该值指示两个指定的 Single 值是否不相等。 |
LessThan(Single, Single) | |
LessThanOrEqual(Single, Single) |
显式接口实现
适用于
线程安全性
此类型的所有成员都是线程安全的。 看起来修改实例状态的成员实际上返回使用新值初始化的新实例。 与任何其他类型一样,读取和写入包含此类型的实例的共享变量必须受到锁的保护,以确保线程安全。
另请参阅
反馈
提交和查看相关反馈