Question how to print double type as it is when there is no decimal point

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

I wonder how to print out the double type as it is without a decimal point and as much as it is. If you output the double type like printf("%f") like this, you get 1.000000.

c c++

2022-09-20 10:54

1 Answers

In a C++ environment, if you just output a double variable with cout, the desired function will be performed. The default setting of cout determines and outputs the decimal place of the real number.

#include <iostream>
using namespace std;

int main()
{
    double x = 1;
    cout << x << '\n';

    x = 1.2;
    cout << x << '\n';
}

There is no function in C that does it automatically, but it has to be implemented directly.

#include <stdio.h>

int main()
{
    double x = 1;

    if (x == (double)((int)x))
        printf("%d", (int)x);
    else
        printf("%lf", x);

    printf("\n");

    x = 1.2;

    if (x == (double)((int)x))
        printf("%d", (int)x);
    else
        printf("%lf", x);

    return 0;
}


2022-09-20 10:54

If you have any answers or tips


© 2022 pinfo. All rights reserved.