Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ different print behavior between values and variables

Tags:

c++

c

printf

I tried the following code on mac, the output is kind of strange to me.

float a = 2.225;
float b = 123.235;
printf("round: %.2f %.2f \n", a, b);
printf("round: %.2f %.2f \n", 2.225, 123.235);

output:

round: 2.22 123.24 
round: 2.23 123.23 

g++ --version

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

What are the rounding rules in printing? How I can get same printing result in these two situations? Many thanks.

like image 944
Jiwei Xu Avatar asked Dec 04 '25 21:12

Jiwei Xu


1 Answers

The first printf() converts the float values to double and then prints the results. Note that the initializations convert the double constants to float. The second passes the double values directly. You can specify float constants with the suffix F — but the rules of C still convert those float constants to double before actually calling printf() because of default argument promotion rules.

#include <stdio.h>

int main(void)
{
    float a = 2.225;
    float b = 123.235;
    printf("round: %.2f %.2f\n", a, b);
    printf("round: %.2f %.2f\n", 2.225, 123.235);
    printf("round: %.2f %.2f\n", 2.225F, 123.235F);

    return 0;
}

Output:

round: 2.22 123.24 
round: 2.23 123.23 
round: 2.22 123.24 
like image 195
Jonathan Leffler Avatar answered Dec 06 '25 11:12

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!