范围极限靠近:)

  今天继续撸一个下载器的时候, 一个 progressbar 控件报 Maximum 超限了

调试看了下,真的会超,Maximum 属性 是 int32 的,但是数据可能会是 long (int64),超限了就会导致崩溃。

 

Lv1:

开始就想着 value/10000 好了

max = org_MaxValue / 10000;
cur = org_CurValue / 10000;
//得到 max 和 cur

 然后想想 觉得 不保险,存在bug,不能就这么算了。

 

Lv2:

因为不知道会超多少, 10000 作除数肯定不保险。

弄个循环判断多少位吧

int n = 0;
long max = org_MaxValue;
while(max < int.MaxValue){
    max /= 10;
    n++;
}
long cur = org_CurValue;
while(n > 0){
    cur /= 10;
    n--;
}
//得到 max 和 cur

 emmmmm,貌似可行的。

但是这样感觉就有点复杂了吧?!

再想想,怎么简单点!

 

Lv3:

然后尝试 用 int.MaxValue 和 long.MaxValue 计算 

42949672963 / 2147483648 = 20.000000001396984
42949672963 / 21         = 2045222522.047619

唉!

2045222522.047619

比 

2147483648

 小唉,

 

 除以 int.MaxValue ,然后向上取整, 或者 取整再加一 作为除数,就能得到肯定比 int.MaxValue 小的数了,

那 cur 的计算等比缩小, 也用 org_CurValue 除以前面的 结果就能得到了。

OK , 可以。

int c = org_MaxValue / int.MaxValue + 1; //或者: Math.Ceiling(org_MaxValue / int.MaxValue)
max = org_MaxValue / c;
cur = org_CurValue / c;
//得到 max 和 cur

然后吧,看着这一除 一除 的,瘆得。

 不就是:`\frac{x}{\frac{x}{y}+1}`

              

 这个公式么。

 然后:`\frac{x}{\frac{x}{y}+1}=\frac{xy}{\frac{xy}{y}+y}=\frac{xy}{x+y}`

              

 所以就有了一个算法了? :)

验证:  

//int.MaxValue=2147483648
//long.MaxValue=9223372036854776000

4294967296*2147483648/(4294967296+2147483648) = 1431655765.3333333 18446744073709552000*2147483648/(18446744073709552000+2147483648) = 2147483647.75 2147483647.75-2147483648 = -0.25 2147483648*2147483648/(2147483648+2147483648) = 1073741824

 

Lv4:

 整理下:

max =(int)(org_MaxValue * int.MaxValue / (org_MaxValue + int.MaxValue));
cur =(int)(org_CurValue * int.MaxValue / (org_CurValue + int.MaxValue));

这样 就整整齐齐了:)

 

 参考:

手写公式转LaTex

 数学公式在线编辑器

(PS: 手写的确很强大, 公式代码复制到在线编辑器, 就能从其html代码里面拷贝到一个在线公式图片)

(PS: 写完了本篇折腾公式显示才发现博客园已经内置了数学公式支持了)

posted @ 2022-05-02 19:50  _Ong  阅读(37)  评论(1编辑  收藏  举报