c++ - 打印浮点值时 printf 崩溃

标签 c++ c printf

今天我遇到了 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() 在这里崩溃了!这向我提出了两个问题:

  1. 我看到了 MSDN 中给出的“FormatOutput(LPCSTR formatstring, ...)”示例,其中他们分配了固定宽度的目标缓冲区,然后用它调用 vsnprintf()。我相信 printf() 的工作原理是相同的。但是我没有在任何地方找到 printf() 的内部缓冲区大小。如果它动态分配内存,那么它如何计算缓冲区大小?

  2. printf() 在上一行崩溃,因为 vsnprintf() 也在那里崩溃(是的,我尝试了 FormatOutput 给出的示例代码vsnprintf() 带有上述参数)。但为什么最终会崩溃?

最佳答案

你 promise 打印 double 但你传递的是 int:987/432 是一个 int。例如,如果您希望此值为 double,您可以使用 987.0/432

关于c++ - 打印浮点值时 printf 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579912/

相关文章:

c++ - 使用 gstreamer 将 jpeg 混合到 mkv

c++ - 使用 boost::interprocess 编译链接器错误

c - C 中无法接受字符串中的空格

c - 在 C 中使用埃拉托斯特尼筛法的素数

ios - 如何生成随机字母数字字符串?

c - 在C中,我想连续打印4个十进制数,然后打印接下来的4个

c++ - 对仅包含 0 和 1 的两个 vector 应用 or(||) 运算符

c++ - SURF opencv 的描述符评估

c++ - 为什么 _stprintf_s 会覆盖其他变量而 _stprintf 不会?

bash - 使用 bash 将十六进制转换为带符号的 64 位