zoukankan      html  css  js  c++  java
  • 浮点数小数点后开始非零数字的起始位置

    有这样一个问题:需要知道浮点数从小数点后,开始非零数字的起始位置。比如: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 && '' != chArr[iIndex]; ++iIndex)
    	{
    		if ('.' == chArr[iIndex])
    		{
    			++iIndex;
    			break;
    		}
    	}
    	
    	// 检索小数点到有效位数之间的长度 
    	for (; iIndex < iLen && '' != chArr[iIndex]; ++iIndex)
    	{
    		if ('0' != chArr[iIndex])
    		{
    			return iPos;
    		}
    		else if (1 != iPos && '' == 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 << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	d = 0.08001;
    	cout << d << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	d = 0.00120;
    	cout << d << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	d = 1.00;
    	cout << d << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	d = 1;
    	cout << d << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	d = 1.0010;
    	cout << d << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	d = 0.10;
    	cout << d << "	 :" << getDoubleAccuracy(d) << endl;
    	
    	getchar();
    	return 0;
    }
    

      

  • 相关阅读:
    使用GZIP压缩网页内容(一)
    使用dom4j工具:xml总结
    使用dom4工具:增删改xml文件(七)
    解决servlet中get方式中中文乱码问题前驱(一):装饰者模式再理解
    解决servlet中get方式中中文乱码问题(二):装饰者模式使用
    使用dom4j工具:获得文本内容(四)
    反射
    Servlet
    JSP
    Http协议
  • 原文地址:https://www.cnblogs.com/hjsstudio/p/9211945.html
Copyright © 2011-2022 走看看