Skip to main content
 首页 » 编程设计

C# 在执行计算时丢失小数分辨率

2024年02月06日15thcjp

当我执行下面的计算时,我似乎失去了十进制分辨率。似乎无论我计算什么数字,我总是以小数点的某个四分之一(例如 x.00、x.25、x.50、0r x.75)结束。谢谢您的帮助。我知道 mph.ToString("n2") 会将其缩减为 2 位小数,但为什么要进入四分之一?

int totalRotations = 0;   
int lastRotations = 0; 
int diffRotations = 0; 
int hourRotations = 0; 
double mph = 0; 
double distance = 0; 
 
 
private void calcMPH() 
{ 
    UInt16 val = CounterInputReader.ReadScanUInt16(); 
 
    totalRotations = val; 
    diffRotations = totalRotations - lastRotations; 
    hourRotations = diffRotations * 3600; 
    distance = hourRotations * 1.8333333;  //wheel constant, (feet/pulse).  Changes per diameter of wheel. 
 
    mph = distance / 5280; 
 
    StatusBox1.Text = StatusBox1.Text + System.Environment.NewLine + "Load Array Rotor Speed:  " + mphWind + " : " + scan.Length; 
 
    sensorScans.Add(Settings1.Default.Ch1c, mph); 
 
    //Why are we losing the decimal point resolution and only limited to quarters (0.00, 0.25, 0.50, 0.75)? 
    lblSpeedValue.Text = mph.ToString("n2") + " mph"; 
 
    lastRotations = totalRotations;  //Save last Rotations per Pulse for mph calculations.   
 
} 

请您参考如下方法:

因为您的计算取决于一个整数,即旋转。最小增量是 1 的 diffRotations。

1 × 3600 × 1.8333333/5280 = 1.25

所以每个 mph 读数总是 1.25 的倍数,例如1.25、2.50、3.75等