什么从printf的同恩pression这个输出COUT有什么不

什么从printf的同恩pression这个输出COUT有什么不

本文介绍了为什么从printf的同恩pression这个输出COUT有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Visual C ++ 2012和命令行编译以下文件:

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

与MSVCRT.LIB而非LIBCMT链接,以避免运行时错误R6002。结果
这是输出的值是0.00000对这一计划的。

Linking with MSVCRT.LIB rather than LIBCMT to avoid runtime error R6002.
The value that is output is 0.00000 for this program.

不过,如果我用C完成同样的事情++

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

现在,它打印出6,像它应该。

Now, it prints out 6, like it should.

有什么区别?难道做的语言本身(C VS C ++)或输出方式(COUT VS printf的),或者是它只是一个怪癖用MSVC?

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?

推荐答案

这位前pression 18/4 + 18%4 计算结果为 INT ,而你请求浮动。你应该总是启用警告编译,并注意它们(他们说的警告是等待发生的错误,他们是正确的)。

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).

这是我的编译器(GCC 4.8.1)告诉我(甚至不执行 -Wall

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’

在另一方面,在的std ::法院&LT;&LT; 操作能够推断出你的前pression的类型和正确的它传输到你的屏幕

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的同恩pression这个输出COUT有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 12:33