C - print float values

I have a C ++ program that takes values ​​and displays the values ​​as follows:

getline(in,number);
cout << setw(10) << number << endl;

I have an equivalent C program that takes values ​​and outputs them like this:

fscanf(rhs, "%e", &number);
printf("%lf\n", number);

But while the C ++ 0.30951program is printing, the C program issues 0.309510. Additional examples include: C ++: 0.0956439C: 0.095644. It seems to print the same results as long as the value is 7 digits, but if it is shorter than 7 digits, it adds an extra 0 at the end. And if it is longer than 7 digits, it is rounded to 6 digits. I would like the C results to match the C ++ program. Any help would be appreciated.

Thank.

Note: the number is a float, and the number is read from the file.

+5
source share
3 answers

C:

printf( "%6.4lf", number );

"" .

, :

int precision = 4;

printf( "%6.*lf", precision, number );
+8

++ iostream s

std::cout.precision(4);
std::cout << std::setw(10) << number << "\n";
+8
printf("%g\n", number); 

Solving your problem,% lf is used for double,% f is used for float, and% g is used for float when you want to display all decimal places and trim zeros.

+4
source

All Articles