格式化C中有效位数的正确答案 [英] Formatting answers to correct number of significant digits in C

查看:231
本文介绍了格式化C中有效位数的正确答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果用户输入两个数字,例如12.5和101.2,在做一些计算之后,程序将返回一个带有3个sigfigs的数字,因为12.5具有最少的有效位数。

我首先需要确定每个数字有多少个sigfig,然后在printf语句中使用格式说明符来使用sigfig规则返回答案。我知道你可以使用像

  printf(。2f,ans)来限制它到特定的小数位数。 ; 

但是我怎么能限制它到数字的特定数字



下面是一个简单计算的例子,您可以考虑重要的数字。

 用户输入12.5,101.2 
ans = 101.2 + 12.5
返回114



答案通常为113.7,但由于12.5只有3位有效数字,所以程序将不得不四舍五入到114. 解决方案

printf()格式说明符%g 有可能指定最大有效位数。从C11(N1570草案)7.21.6.1/4(重点是我的):


一个可选的精度,使最小位数为$ b,b出现在d,i,o,u,x和X转换中,a,e,E,f和F $的小数点后面出现的位数
b $ b转换,g和G
转换的最大有效位数,...

因此,在您的情况下,可以将结果限制为三位有效数字,如:

$ p $ #include
int main(void)
{
double ans = 101.2 + 12.5;

printf(%。3g \\\
,ans);

返回0;

$ / code $ / pre
$ b $结果:

  114 

请注意,% g 可能会在其他情况下选择科学记数法。


For example, if the user inputs two numbers such as 12.5 and 101.2, after doing some calculations the program would return a number with 3 sigfigs since 12.5 has the least amount of significant digits.

I would first need to determine how many sigfigs each number has, and then use format specifiers in the printf statement to return the answer using sigfig rules. I know that you can restrict it to a specific number of decimal places using something like

printf(".2f",ans);

but how can I restrict it to a specific number of digits?

Here's an example of a simple calculation you could make taking significant figures into account.

user inputs 12.5, 101.2
ans=101.2+12.5
return 114

The answer would normally be 113.7, but since 12.5 only has 3 significant digits the program would have to round it to 114.

解决方案

One of printf() format specifiers %g has possibility to specify maximum number of significant digits. From C11 (N1570 draft) 7.21.6.1/4 (emphasis mine):

An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, ...

Thus in your case it's possible to restrict result into three significant digits like:

#include <stdio.h>

int main(void)
{
    double ans = 101.2 + 12.5;

    printf("%.3g\n", ans);

    return 0;
}

Result:

114

Note however that %g may choose scientific notation in some other cases.

这篇关于格式化C中有效位数的正确答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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