今天我遇到了 printf()
的奇怪问题。但即使在分析之后我也找不到它的答案。因此在这里分享。我尝试了这三个 printf()
语句:
printf("\nValue of this division is %f", (double)873/(double)65);
它按预期打印正确的输出。
printf("\nSome message with an integer here %d followed by floats %f, %f, %f", 2013, 987/432, 873/65, 983/81);
给我错误的值(因为我没有将它们加倍?)
printf("\nSome message with an integer here %d followed by floats %f, %f, %f and now string at end: %s", 2013, 987/432, 873/65, 983/81, "Some trial string here");
printf()
在这里崩溃了!这向我提出了两个问题:
我看到了 MSDN 中给出的“FormatOutput(LPCSTR formatstring, ...)”示例,其中他们分配了固定宽度的目标缓冲区,然后用它调用
vsnprintf()
。我相信printf()
的工作原理是相同的。但是我没有在任何地方找到printf()
的内部缓冲区大小。如果它动态分配内存,那么它如何计算缓冲区大小?printf()
在上一行崩溃,因为vsnprintf()
也在那里崩溃(是的,我尝试了FormatOutput
给出的示例代码vsnprintf()
带有上述参数)。但为什么最终会崩溃?
最佳答案
你 promise 打印 double
但你传递的是 int
:987/432
是一个 int
。例如,如果您希望此值为 double
,您可以使用 987.0/432
。
关于c++ - 打印浮点值时 printf 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579912/