C ++:我如何测试一个数字是十的幂? [英] C++: how can I test if a number is power of ten?

查看:154
本文介绍了C ++:我如何测试一个数字是十的幂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个数字 double x 是一个10的整数次幂。我可以使用cmath的 log10 然后测试 x ==(int)x

I want to test if a number double x is an integer power of 10. I could perhaps use cmath's log10 and then test if x == (int) x?

edit:事实上,我的解决方案不工作,因为双重可以是非常大,比int大得多,也很小,像分数。

edit: Actually, my solution does not work because doubles can be very big, much bigger than int, and also very small, like fractions.

推荐答案

p>查找表将是迄今为止最快和最精确的方法来做到这一点;只有大约600的10的幂可以表示为双。您可以使用哈希表,或者如果表从最小到最大排序,您可以使用二进制数快速搜索。

A lookup table will be by far the fastest and most precise way to do this; only about 600 powers of 10 are representable as doubles. You can use a hash table, or if the table is ordered from smallest to largest, you can rapidly search it with binary chop.

这样做的好处是,一个命中,当且仅当你的数字是最接近的可能IEEE双倍的一些权力10.如果这不是你想要的,你需要更准确的你想要你的解决方案如何处理事实10的许多权力不能被精确地表示为双精度。

This has the advantage that you will get a "hit" if and only if your number is exactly the closest possible IEEE double to some power of 10. If this isn't what you want, you need to be more precise about exactly how you would like your solution to handle the fact that many powers of 10 can't be exactly represented as doubles.

构造表的最好方法是使用string - > float conversion;希望你的图书馆作者已经解决了如何进行转换的问题,以提供最准确的答案。

The best way to construct the table is probably to use string -> float conversion; that way hopefully your library authors will already have solved the problem of how to do the conversion in a way that gives the most precise answer possible.

这篇关于C ++:我如何测试一个数字是十的幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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