The difference between cout and printf in C++
PHPz
PHPz 2017-05-16 13:24:08
0
5
1716

As shown in the following code, there is a difference between cout and printf when outputting data.

double ans = 0, max = 135.349, min = 3.88633;
ans = max * 2086458231 / min;
cout << ans << endl;
printf("%lf", ans);

Output

7.26652e+010
72665192664.000000

Why is there such a difference?

PHPz
PHPz

学习是最好的投资!

reply all(5)
習慣沉默

Formatted output problem of c++, cout’s default output format of floating point numbers is not %lf. If you want to set the output format, you can refer to the following link
http://en.cppreference.com/w/...

#include <iostream>

int main() {
    double ans = 0, max = 135.349, min = 3.88633;
    ans = max * 2086458231 / min;


    std::cout << ans << std::endl;  // 7.2665e+10

    std::cout.setf(std::ios::scientific);
    std::cout << ans << std::endl;  // 7.266497e+10

    std::cout.unsetf(std::ios::scientific);
    std::cout.setf(std::ios::fixed);
    std::cout << ans << std::endl;  // 72664965432.070602

    printf("%lg\n", ans);   // 7.2665e+10
    printf("%lf\n", ans);   // 72664965432.070602

    return 0;
}
巴扎黑

cout is the syntax of C++, printf is the C language, but C is retained. In cstdio, the results are different because cout defaults to retaining N bits + scientific calculation method for over-long floating point numbers, but cout can also be used Use parameters to format the output, such as
cout << setiosflags(ios::fixed) << f
No need for scientific notation. You can consult the manual for more parameters.
printf can also be formatted, very Convenient

我想大声告诉你

coutThe default stream output valid bits are 6 digits. If it exceeds 6 digits, it will be automatically formatted. If the integer length exceeds 6 digits, it will be automatically formatted into scientific notation.

淡淡烟草味

cin and cout are c++ codes, printf and scanf are c codes. %f in C language outputs floating-point data in decimal form.

漂亮男人

cout is the output method in the c++ iostream standard library, while printf is retained by the c language. The default formatted output of cout is different from %lf

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template