繁体   English   中英

不能增加浮点变量的值

[英]Can't increment value of a floating-point variable

我是C#的新手,我无法理解,为什么我的变量不想增加到大于16777215的值。

我有代码:

float fullPerc = 100;
float bytesRead = 1;
long fileSize = 1;
ProgressBar pb1;
int blockSizeBytes = 0;
float counter = 0;

using (FileStream inFs = new FileStream(inFile, FileMode.Open))
{
    fileSize = inFs.Length;
    do
    {
        counter = counter + 1;
        if (counter > 16777215) //&& counter < 16777230)
        {
            counter = counter + 10;
            //Console.WriteLine(((counter + 10) /100));
        }
        count = inFs.Read(data, 0, blockSizeBytes);
        offset += count;
        outStreamEncrypted.Write(data, 0, count);

        bytesRead += blockSizeBytes;

   }
   while (count > 0);
   inFs.Close();
}

https://bitbucket.org/ArtUrlWWW/myfileencoderdecoder/src/f7cce67b78336636ef83058cd369027b0d146b17/FileEncoder/Encrypter.cs?at=master&fileviewer=file-view-default#Encrypter.cs-166

当计数器的值等于16777216时,可变增量counter = counter + 1;代码counter = counter + 1; 不起作用,但是这段代码

if (counter > 16777215) //&& counter < 16777230)
                                    {
                                        counter = counter + 10;
                                        //Console.WriteLine(((counter + 10) /100));
                                    }

很好。

即,如果我if代码中对此注释,则我的counter将增长到16777216的值并将停止在该值上。 当此变量> = 16777216时,仅将其递增10即可。

为什么?

您的尾数溢出 ,结果是精度损失 float (或Single )类型的尾数为24位(最多16777216 ):

https://en.wikipedia.org/wiki/Single-precision_floating-point_format

让我们看看发生了什么:

  private static String MakeReport(float value) {
    return String.Join(" ", BitConverter
     .GetBytes(value)
     .Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));
  }

...

  float f = 16777215;

  // Mantissa (first 3 bytes) is full of 1's except the last one bit
  // 11111111 11111111 01111111 01001011
  Console.Write(MakeReport(f)); 

  // Overflow! Presision loss
  // 00000000 00000000 10000000 01001011  
  Console.Write(MakeReport(f + 1)); 

  // Overflow! Presision loss
  // 00000000 00000000 10000000 01001011  
  Console.Write(MakeReport(f + 2)); 

  // Overflow! Presision loss
  // 00000100 00000000 10000000 01001011  
  Console.Write(MakeReport(f + 10)); 

补救措施:不要将浮点数用作counter而应使用整数

 int counter = 0;

避免整数除法将值转换为double

  float x = (float) ((((double)counter * blockSizeBytes) / fileSize) * fullPerc);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM