如何计算整数的十进制数字?

How to count decimal digits of an integer?

本文关键字:整数 十进制数字 计算 何计算      更新时间:2023-10-16

我写了一个程序来确定数字中的位数

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long num1 = 1999999999999999;
long long num2 = 9999999999999999;
int number_of_digit_1 = log10(num1) + 1;
int number_of_digit_2 = log10(num2) + 1;
cout << number_of_digit_1 << endl;
cout << number_of_digit_2 << endl;
}

输出是这样的

16 
17

即使它应该打印相同的数字 (16(。为什么会这样?

log10将各种浮点类型作为参数,并在其结果中返回相同的类型。在您的情况下,它正在转换为double.

double只有53位用于它的整数(有效(部分。

9999999999999999需要 54 位才能准确表示。

当您将9999999999999999转换为double时,您会得到10000000000000000因此log10(9999999999999999)16的结果是意料之中的。

要获得整数中的准确(并且可能更快(的位数计数,您应该使用整数方法来计算数字。有多种技术,例如在现代 x86-64 上计算 64 位整数的整数 Log10 的最快方法是什么?或 http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog

未定义log10(long long int)。然后,num2被隐式转换为精度较低的double。将num2转换为long double可以解决此问题。

此解决方法不适用于 Visual Studio(在那里,double = long double(。但是,它适用于 gcc 和 clang。

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long num1 = 1999999999999999;
long long num2 = 9999999999999999;
long double x = static_cast<long double> (num2);
int number_of_digit_1 = log10(num1) + 1;
int number_of_digit_2 = log10(num2) + 1;
int number_of_digit_3 = log10(x) + 1;
cout << number_of_digit_1 << endl;
cout << number_of_digit_2 << endl;
cout << number_of_digit_3 << endl;
}

另一种可能性是使用简单的专用函数来计算位数,通过简单的while循环。通常,在这种情况下,效率不是问题。

template <typename T> 
int n_digits (T num) {
int n = 0;
while (num != 0) {
++n;
num /= 10;
}
return n;
}