search

Home  >  Q&A  >  body text

The difference between cout and printf in C++

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?

PHPzPHPz2750 days ago1651

reply all(5)I'll reply

  • 習慣沉默

    習慣沉默2017-05-16 13:26:08

    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;
    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:26:08

    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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:26:08

    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.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:26:08

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

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 13:26:08

    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

    reply
    0
  • Cancelreply