为什么从printf的同一个表达式的输出不同于cout? [英] Why does this output of the same expression from printf differ from cout?
问题描述
我使用Visual C ++ 2012并从命令行编译以下文件:
#include< stdio。 h。
int main()
{
printf(%。5f,18/4 + 18%4);
return 0;
}
使用MSVCRT.LIB而不是LIBCMT链接,以避免运行时错误R6002。 >
此程序的输出值为0.00000。
但是,如果我在C ++中执行完全相同的事情
#include< iostream>
using namespace std;
int main()
{
cout<< 18/4 + 18%4 < endl
return 0;
}
现在,它打印出6, b
$ b
有什么区别?是与语言本身(C对C ++)还是输出方法(cout vs printf),还是只是MSVC的怪癖?
表达式 18/4 + 18%4
计算为 int
请求浮动。你应该总是编译警告启用,并注意他们(他们说一个警告是一个bug等待发生,他们是对的)。
这是我的编译器(GCC 4.8.1)告诉我(甚至没有强制执行 -Wall
):
警告:格式'%.5f'期望类型为'double',但参数2类型为'int'
另一方面, std :: cout<<
操作能够推导出您的表达式的类型,并将其正确地流式传输到您的屏幕上。
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 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.
这篇关于为什么从printf的同一个表达式的输出不同于cout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!