c ++如何获得“一位数指数”与printf [英] c++ how to get "one digit exponent" with printf

查看:105
本文介绍了c ++如何获得“一位数指数”与printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以用科学计数法打印少于3个位数的指数部分?
6.1格式不会影响指数,而只会影响数字部分:

Is there a way to print in scientific notation less than 3 places for exponent part of number? The 6.1 formatting doesn't affect exponent but only the number part:

var=1.23e-9;
printf ("%e\n", var);
printf ("%6.1e\n", var);

给予

1.230000e-009
1.2e-009

我也尝试过在wxWidgets中具有字符串格式,但行为是相同的。

I've also tried this in wxWidgets with formatting of string but the behavior is the same.

m_var->SetLabel(wxString::Format(wxT("%6.1e"),var));

我想要的是 1.2e-9

推荐答案

我不得不做很多事情(我编写了文件解析器和一些文件格式,例如NITF要求您将数值存储为字符串。)

I've had to do this a lot (I write file parsers and some file formats like NITF require you to store numeric values as strings).

您要做的是利用以10为基数的数学(科学记数法)的真正含义为基础的漏洞利用:实数y,y =(x)* 10 ^(N)对于某个整数N和一些x在(-1,1)范围内。

What you do is an exploit based on what base-10 math (scientific notation) really means: It means that for all real numbers y, y = (x) * 10^(N) for some integer N and some x in the range (-1, 1) exclusive.

您可以执行以下操作

void PrintScientific(double d)
{
   int exponent  = (int)floor(log10( fabs(d)));  // This will round down the exponent
   double base   = d * pow(10, -1.0*exponent);

   printf("%lfE%+01d", base, exponent);
}

您可以添加所有需要控制字符数的格式说明符, 之后 。小数点后的位置。

You can add all the format specifiers you need to control the # of chars before, after the "." decimal place.

不要忘记舍入步骤!使用base10和对数(此处为10)的属性,这就是它的工作方式:


让y = x * 10 ^ N =>

log (y)= log(x * 10 ^ N)=>

log(y)= log(x)+ log(10 ^ N)=> //从日志乘积规则

log(y)= log(x)+ N

Do NOT forget the rounding step! This is how it works, using the properties of base10 and logarithms (base 10 here):

Let y = x * 10^N =>
log(y) = log(x*10^N) =>
log(y) = log(x) + log(10^N) => // From Log "product" rule
log(y) = log(x) + N

由于x的范围是(-10,10)- ()表示互斥(独占),这意味着log(x)在(-1,1)范围内。因此,当我们舍入为整数转换时,我们将删除 log(x)贡献。
然后,您可以从原始数字中获取 x部分,从而可以使用任何要使用的科学计数法输出原始文件。

Since x is in the range (-10, 10) -"()" means exclusive(exclusive), that implies log(x) is in the range (-1, 1). So when we round down for integer conversion, we're dropping "log(x)" contribution. You can then get the "x" portion from the original number, which lets you output the original in any scientific notation you want to use.

这篇关于c ++如何获得“一位数指数”与printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆