无法增加浮点变量的值

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;不起作用,但是这段代码

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

工作正常。

即,如果我注释此 if 代码,我的 counter 将增长到 16777216 值并将停止在该值上。当这个变量 >=16777216 .

时,只有增加 10 才会增加这个变量

为什么?

您有尾数 溢出,结果是 presision lossfloat(或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);