c# - 通过整数进行分数计数

标签 c# algorithm

我收到一个整数,表示小数面额的美元金额。我想要一种可以将这些数字相加而无需解析并将它们转换为 double 或小数的算法。

例如,我收到整数 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 还是有问题,但至少好一些。

关于c# - 通过整数进行分数计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2230361/

相关文章:

c# - 在C# 7.0中使用反射获取不包括本地函数的方法?

c# - 反序列化和构造函数的关系

c# - 通过 .Net 代码加载和使用 Mathematica 包

algorithm - 将任意 GUID 编码为可读的 ASCII (33-127) 的最有效方法是什么?

arrays - 您如何迭代属于同一大小为 n 的域的 m 个变量的所有配置?

algorithm - BST 到链表并返回同一个 BST

c# - 在共享主机中在 IIS/WCF 下触发线程/进程的最佳方法

c# - twain driver with xerox workcentre

algorithm - 如何使用二进制搜索解决以下问题?

algorithm - 如何执行图顶点覆盖的整数线性规划公式的松弛?