如何检查数字是否可以在c#中分割? [英] How to check if number is divisible in c#?

查看:152
本文介绍了如何检查数字是否可以在c#中分割?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何执行此操作。

  calculate1:​​1/4 = 0,25 
计算2:1/8 = 0,125
计算3:47/183 = 0,25683060109289617486338797814207 ......
计算4:58/889 = 0,06524184476940382452193475815523 ......
计算5 :1/5 = 0,2

计算结果1,2和5将给出一个简短的结果,没有时期或无尽的数字字符串。计算3和4的结果非常长而复杂。



我如何检查哪种计算是简单的,并给出短结果。 p>

我试过这个,它给了一个错误的结果肯定...
像你可以看到,计算结果的数据类型

  static bool IsInt(double x)
{
try
{
int y = Int32.Parse(x.ToString());
返回true;
}
catch
{
return false;
}
}

我希望很清楚我在问什么。

解决方案

如果在尽可能减少分数之后,分母可以表示为2的幂乘以5,则十进制表示终止。否则会无限期重复。<​​/ p>

您可以测试您的部门是否好如下:

  public bool IsGoodDivision(int a,int b)
{
while(b%2 == 0){b / = 2; }
while(b%5 == 0){b / = 5; }
return a%b == 0;
}

看到它在线工作: ideone



请注意,我将分子和分母分别传递给方法。如果您先进行分割,然后将结果传递给您的方法,则由于浮点表示失去精度错误



此外,对于生产代码,您应该检查 b!= 0 ,因为它不是允许除以0.没有检查,上述代码将进入无限循环。


I need to know how to do this procedure.

calculation1: 1/4 = 0,25
calculation2: 1/8 = 0,125
calculation3: 47/183 = 0,25683060109289617486338797814207......
calculation4: 58/889 = 0,06524184476940382452193475815523......
calculation5: 1/5 = 0,2

The results of calculations 1, 2 and 5 will give a short result, no periods or and endless string of digits. The results of calculations 3 and 4 are very long and complicated.

How can I check which calculation is an "easy one" and gives a "short" result.

I tried this and it gave a wrong result for sure... like you can see, the results of the calculations have the datatype double in my application.

static bool IsInt(double x)
    {
        try
        {
            int y = Int32.Parse(x.ToString());
            return true;
        }
        catch
        {
             return false;
        }
    }

I hope it is clear what I'm asking.

解决方案

If after reducing the fraction as much as possible, the denominator can be expressed as a power of 2 multiplied by a power of 5, then the decimal representation terminates. Otherwise it repeats indefinitely.

You could test if your division is "good" as follows:

public bool IsGoodDivision(int a, int b)
{
    while (b % 2 == 0) { b /= 2; }
    while (b % 5 == 0) { b /= 5; }
    return a % b == 0;
}

See it working online: ideone

Note that I am passing the numerator and denominator separately to the method. If you do the division first, then pass the result to your method, you lose precision due to floating point representation error.

Also for production code you should check that b != 0 because it is not allowed to divide by 0. Without the check the above code would go into an infinite loop.

这篇关于如何检查数字是否可以在c#中分割?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆