有没有办法告诉小数在C#中是终止还是重复? [英] Is there a way to tell if a decimal is terminating or repeating in C#?

查看:142
本文介绍了有没有办法告诉小数在C#中是终止还是重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何知道分数中的重复小数?

Possible Duplicate:
How to know the repeating decimal in a fraction?

有没有办法判断小数点是终止还是重复?

Is there a way to tell if a decimal is terminating or repeating?

示例: 我有分数:1/3,并且它是重复的小数-0.33333333333333333333 我有分数1/2,它的结尾是小数-0.5

Example: I have fraction: 1/3 and it's repeating decimal - 0.33333333333333333333 I have fraction 1/2 and it's terminating decimal - 0.5

我不知道该怎么做.

推荐答案

根据 Wikipedia ,如果分数可以以k/(2^n * 5^m)的形式表示,则其中k,n和m为整数.

According to Wikipedia, A fraction is terminating if it can be represented in the form of k/(2^n * 5^m), where k, n, and m are integers.

#assumes that the fraction is already fully reduced
#e.g. numerator and denominator are coprime
function isTerminating(numerator, denominator):
    while denominator % 2 == 0:
        denominator /= 2
    while denominator % 5 == 0:
        denominator /= 5
    return denominator == 1

如果您的分数在IEEE浮点数中,则只要它不是NaN或+/-无穷大,它就总是终止.浮点数中的有限数字表示为c * b^q.可以将这些术语重新排列为c / (b^-q). b始终为2或10,因此该数字符合k/(2^n * 5^m)格式,因此为终止分数.

If you have the fraction in an IEEE float, then it always terminates, as long as it is not NaN or +/- infinity. Finite numbers in floats are represented as c * b^q. The terms may be rearranged to be c / (b^-q). b is always 2 or 10, so the number fits the k/(2^n * 5^m) format and is therefore a terminating fraction.

这篇关于有没有办法告诉小数在C#中是终止还是重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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