Home > Software engineering >  how to print double exactly as input in C
how to print double exactly as input in C

Time:08-10

In c language, for example:

if value double x = 3.4900

I want output be 3.4900, not 3.490000

The problem is the input value x is changeable, I don't how many decimal point will be.

any idea?

CodePudding user response:

to make an answer:

double x = 3.4900;

printf("the value of x is %.4f",x);

.4 means, you print the value with for digits after the dot. If you want to print exact and changeable number of digits you read in, you had to work with a string.

CodePudding user response:

double x = 3.4900; is exactly the same as double x = 3.49;

When you ask about "input", you might mean "reading a value as a string from a file or stdin"... You could count the digits to the right of the decimal point and store that count in another variable.

Once that string is converted to double, there is no record of how much 'precision' was supplied by the source.

And, because floats and doubles use base-2 numbers (not base-10), it is extremely rare that the internal representation matches the base-10 version (without some rounding involved.)

Note in the following the 'extra effort' to determine the precision from the pseudo-input string...

int main() {
    char *s1 = "3.4900";
    char *s2 = "3.49";

    double d1 = strtod( s1, NULL );
    double d2 = strtod( s2, NULL );

    printf( "%s\n", d1 == d2 ? "Same" : "Diff!!" );

    char *cp = strchr( s1, '.' )   1;
    int prec = strlen( s1 ) - (cp - s1);
    printf( "s1 restores as %.*lf\n", prec, d1 );

    return 0;
}

CodePudding user response:

any idea?

C programming language does not have reflection - it's not possible to inspect itself. If you want to have the ability to inspect the source code of a C program from that C program itself, you have to implement such functionality yourself.

how to print double exactly as input in C

You have to include verbatim the stringifed form of the input inside your source code and print that.

double x = 3.4900;
const char *xstr = "3.4900";
printf("source code %s was translated into %f\n", xstr, x);

With the help of # preprocessor operator, we could make it a bit nicer and don't repeat ourselves:

struct double_and_string {
   double x;
   const char *str;
};
#define VAL_AND_STR(x)   { x, #x }
struct double_and_string a = VAL_AND_STR(3.4900);
printf("source code %s was translated into %f\n", a.str, a.x);

CodePudding user response:

double x = 3.4900;

printf("the value of x is %lf",x);
  • Related