Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting answers to correct number of significant digits in C

Tags:

c

formatting

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.

like image 870
slayer Avatar asked Nov 02 '14 17:11

slayer


1 Answers

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.

like image 174
Grzegorz Szpetkowski Avatar answered Sep 25 '22 09:09

Grzegorz Szpetkowski