c# – 通过整数进行分数计数
发布时间:2020-12-15 17:49:25 所属栏目:百科 来源:网络整理
导读:我收到一个整数,表示小数面额的美元金额.我想要一种算法,可以添加这些数字而无需解析并将它们转换为双精度或小数. 例如,我收到整数50155,这意味着50和15.5 / 32美元.然后我收到10210,即10和21/32美元.所以50 15.5 / 32 10 21/32 = 61 4.5 / 32,因此: 50155
我收到一个整数,表示小数面额的美元金额.我想要一种算法,可以添加这些数字而无需解析并将它们转换为双精度或小数.
例如,我收到整数50155,这意味着50和15.5 / 32美元.然后我收到10210,即10和21/32美元.所以50 15.5 / 32 10 21/32 = 61 4.5 / 32,因此: 50155 10210 = 61045 我想再次避免这种情况: int a = 50155; int b = a / 1000; float c = a % 1000; float d = b; d += c / 320f; // d = 50.484375 我更喜欢这个: int a = 50155; int b = 10210; int c = MyClass.Add(a.b); // c = 61045 ... public int Add(int a,int b) { // ????? } 在此先感谢您的帮助! 解决方法
好吧,我不认为你需要使用浮点…
public static int Add(int a,int b) { int firstWhole = a / 1000; int secondWhole = b / 1000; int firstFraction = a % 1000; int secondFraction = b % 1000; int totalFraction = firstFraction + secondFraction; int totalWhole = firstWhole + secondWhole + (totalFraction / 320); return totalWhole * 1000 + (totalFraction % 320); } 或者,您可能希望创建一个可以转换为整数格式的自定义结构,并重载运算符.这将允许您编写更易读的代码,这些代码不会意外地导致其他整数被视为这种略微奇怪的格式. 编辑:如果你被迫坚持使用“单整数”格式,但要稍微调整一下你可能要考虑使用512而不是1000.这样你可以使用简单的掩码和移位: public static int Add(int a,int b) { int firstWhole = a >> 9; int secondWhole = b >> 9; int firstFraction = a & 0x1ff int secondFraction = b & 0x1ff; int totalFraction = firstFraction + secondFraction; int totalWhole = firstWhole + secondWhole + (totalFraction / 320); return (totalWhole << 9) + (totalFraction % 320); } 仍然有320的混乱,但它至少有点好. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |