Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Printing out float values

I have a C++ program that takes in values and prints out values like this:

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

I have an equivalent C program that takes in values and prints out like so:

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

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

Thanks.

Note: number is a float and number are read from a file.

like image 937
FidelCashflo Avatar asked Mar 19 '13 21:03

FidelCashflo


People also ask

How do I print float numbers upto 1 decimal C?

Use "%. By using this format specifier we can print specific number of digits after the decimal, here "n" is the number of digits after decimal point.

How do you print a float in Objective C?

Try formatting the float like this: NSLog(@"%. 2f", myFloat); The % sign means this will be replaced by the corresponding argument following ( myFloat ).

Can I use %d for float?

So, you can see here that %d is used for integers, %f for floats and %c for characters. As simple as that!


2 Answers

Take advantage of the length and precision specifiers in C formatted print statements:

printf( "%6.4lf", number );

Prints four decimal places in a "cell" six characters wide.

You can use a wildcard character for either length or precision to provide that value at runtime:

int precision = 4;

printf( "%6.*lf", precision, number );
like image 159
Bob Kaufman Avatar answered Sep 27 '22 00:09

Bob Kaufman


Take advantage of the length and precision specifiers in C++ iostreams

std::cout.precision(4);
std::cout << std::setw(10) << number << "\n";
like image 42
Alex Chamberlain Avatar answered Sep 27 '22 00:09

Alex Chamberlain