问题
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.
回答1:
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.
回答2:
According to the specs, you can't format the number this way. printf -
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces.
The value is not truncated even if the result is larger.
You will need to provide your own function to "partially" print sigfigs of a float variable.
回答3:
The format specifier %e forces scientific notation. Use precision along with it to force the number of significant digits. For example,
printf("%.2e\n", 101.2+12.5);
outputs
1.14e+02
来源:https://stackoverflow.com/questions/26701919/formatting-answers-to-correct-number-of-significant-digits-in-c