显示有效数字的数值数据策略






2.33/5 (6投票s)
2002年12月6日

62528
使用 Log10 显示具有有效数字的数值数据的一种策略。
引言
问题:有时数值数据,例如浮点数和双精度数,需要以一定的精度显示,并且有时需要以给定的有效数字显示。
例如
4.5568 displayed with 2 Significant Figures is: 4.6
0.0221 displayed with 3 Significant Figures is: 0.022
5.9 displayed with 1 Significant Figures is: 6
策略:使用 log10
函数,我们可以计算数字整数部分的位数。可以使用 sprintf
调用或其他类似方法正确显示数字的小数部分,如我们在下面的函数中所见。此解决方案还会对最终数字进行四舍五入,这通常是在显示有效数字时期望的。
double CalculateSigFig(double num, int sigfig) { char buff[128];//temp buffer double temp = 0; int lognum = 0; std::string formatbuff;//format string if(sigfig <= 0 || num == 0)//damage control return num; temp = int(num); if(temp * -1 > 0)//check for negative numbers temp *= -1; lognum = (int)log10(temp);//get significant digits of integer part of num ++lognum; //adjust for log10 results sigfig -= lognum;//subtract for decimal precision calculation if(sigfig < 0)//check for negative results sigfig = 0; //construct format string formatbuff = "%"; itoa(lognum, buff, 10);//convert lognum to int formatbuff += buff; formatbuff += "."; itoa(sigfig, buff, 10); formatbuff += buff; formatbuff += "f"; //end construct format string //use format string to get desired results sprintf(buff, formatbuff.c_str(), num); return atof(buff);//return double converted from string }