I'm using Visual C++ 2012 and compiling from the command line the following files:
#include <stdio.h> int main() { printf("%.5f", 18/4+18%4); return 0; }
Linking with MSVCRT.LIB rather than LIBCMT to avoid runtime error R6002.
The value that is output is 0.00000 for this program.
However, if I perform the exact same thing in C++
#include <iostream> using namespace std; int main() { cout << 18/4+18%4 << endl; return 0; }
Now, it prints out 6, like it should.
What's the difference? Is it to do with the languages themselves (C vs C++) or the output methods (cout vs printf), or is it just a quirk with MSVC?
The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf(). As pointed out above, printf is a function, cout an object.
Depending on what you print, either may be faster. printf() has to parse the "format" string and act upon it, which adds a cost. cout has a more complex inheritance hierarchy and passes around objects. In practice, the difference shouldn't matter for all but the weirdest cases.
@rashedcs printf is definitely faster than cout because of internal syncing / flushing in iostream i/o which normally slows down their performance. However using iostream with sync_with_stdio(false) makes i/o operations comparable to scanf/printf.
cout is used in C++ to display whatever you want when print is used in python for the same purpose. Every programming language has different method for this for ex; Java ==> System.
The expression 18/4+18%4
evaluates to an int
, and you are requesting a float. You should always compile with warnings enabled, and pay attention to them (they say a warning is a bug waiting to happen, and they are right).
This is what my compiler (GCC 4.8.1) tells me (and even without enforcing -Wall
):
warning: format ‘%.5f’ expects type ‘double’, but argument 2 has type ‘int’
On the other hand, the std::cout<<
operation is able to deduce the type of your expression and correctly stream it to your screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With