如何计算整数的十进制数字?
How to count decimal digits of an integer?
我写了一个程序来确定数字中的位数
#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;
}
相关文章:
- 检查输入是否不是整数或数字
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 如何计算整数的十进制数字?
- Unicode Chars显示为十进制数字而不是符号,我该如何修复
- 根据参数设置十进制数字
- 将二进制号转换为十进制数字的代码
- 为什么它在循环 C++ 中反转整数的数字
- 使用动态比特斯转换十进制数字
- 此代码中 * 1233 >> 12 计算十进制数字背后的数学原理是什么
- 每个值64位整数的数字应转换为位等效的64位浮数
- 仅使用char将八分音号码转换为十进制数字
- 将十进制数字截断为最接近的4个小数和断言
- 打印长双变量的所有十进制数字
- 十进制数字的区域设置感知编辑控件子类化(格式[sign][xxx..][decimal separator][yy.])
- 将双精度转换为精度超过 5 位十进制数字的字符串
- 提取整数的数字元素
- C++:将整数的数字分成相等的部分
- 将双十进制数字转换为HEX字符串
- 如何确定浮点数中的最后一个非零十进制数字
- 如何用C++将给定整数的数字分隔开