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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With