浮点数小数点后开始非零数字的起始位置
有这样一个问题:需要知道浮点数从小数点后,开始非零数字的起始位置。比如:1.05,非零位置就是2;0.004200,非零位置就是3。具体效果如下图:
代码:
#include <iostream> #include <iomanip> #include <stdio.h> using namespace std; int getDoubleAccuracy(double d) { char chArr[100] = ""; int iIndex = 0; int iPos = 1; int iLen = sprintf(chArr, "%lf", d); // 检索小数点位置 for (; iIndex < iLen && '\0' != chArr[iIndex]; ++iIndex) { if ('.' == chArr[iIndex]) { ++iIndex; break; } } // 检索小数点到有效位数之间的长度 for (; iIndex < iLen && '\0' != chArr[iIndex]; ++iIndex) { if ('0' != chArr[iIndex]) { return iPos; } else if (1 != iPos && '\0' == chArr[iIndex]) { return 0; } else { ++iPos; } } return 0; } int main(int argc, char *argv[]) { double d = 0.001; cout.setf(ios::fixed); cout.precision(6); cout << d << "\t :" << getDoubleAccuracy(d) << endl; d = 0.08001; cout << d << "\t :" << getDoubleAccuracy(d) << endl; d = 0.00120; cout << d << "\t :" << getDoubleAccuracy(d) << endl; d = 1.00; cout << d << "\t :" << getDoubleAccuracy(d) << endl; d = 1; cout << d << "\t :" << getDoubleAccuracy(d) << endl; d = 1.0010; cout << d << "\t :" << getDoubleAccuracy(d) << endl; d = 0.10; cout << d << "\t :" << getDoubleAccuracy(d) << endl; getchar(); return 0; }