写代码, 无意中摸了下算法:)
2022/5/2 20:43:28
本文主要是介绍写代码, 无意中摸了下算法:),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
今天继续撸一个下载器的时候, 一个 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
然后吧,看着这一除 一除 的,瘆得。
不就是:
![This is the rendered form of the equation. You can not edit this directly. Right click will give you the option to save the image, and in most browsers you can drag the image onto your desktop or another program.](/images/baidian.png)
这个公式么。
然后:
![This is the rendered form of the equation. You can not edit this directly. Right click will give you the option to save the image, and in most browsers you can drag the image onto your desktop or another program.](/images/baidian.png)
所以就有了一个算法了? :)
验证:
//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代码里面拷贝到一个在线公式图片)
这篇关于写代码, 无意中摸了下算法:)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现