为什么程序不执行最终的 printf 语句? [英] Why does program not execute final printf statement?

查看:18
本文介绍了为什么程序不执行最终的 printf 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么程序控制没有到达第三个 printf,就在 for 循环之后.

I cannot figure out why program control does not reach the third printf, right after the for loop.

为什么第三个 printf 不打印?

Why won't the third printf print?

如果我将 for 循环更改为 while 循环,它仍然不会打印.

If I change the for loop to while loop, it still will not print.

这是程序和输出:

main()
{
    double nc;

    printf ("Why does this work, nc = %f
", nc);
    for (nc = 0; getchar() != EOF; ++nc)
    {
        printf ("%.0f
", nc);
    }
    printf ("Why does this work, nc = %f", nc);
}

输出为:

Why does this work, nc = 0.000000
test
0
1
2
3
4

推荐答案

它对我来说很好用,你想如何终止程序?当 getchar() 检测到 EOF 作为输入时,for 循环应该结束.

It works fine for me, how are you trying to termintate the program? The for-loop should end once EOF is detected as input by getchar().

EOF 在 Windows 下是 Control-Z (^Z) 和 Control-D (^D) 在 Linux/Unix 下.一旦我输入这个,循环终止,我得到最终的 printf() 来显示它的输出.

EOF is Control-Z (^Z) under Windows and Control-D (^D) under Linux/Unix. Once I enter this, the loop terminates and I get the final printf() to display its output.

作为最后一点(正如@DanielFisher 也提到的),在最后的 printf() 调用末尾添加一个 ' ' ,因为它可能是您的特定实现要求,否则程序的行为可能未定义(感谢 @KeithThompson 和 @AndreyT 在评论中指出这一点):

As a final note (as mentioned by @DanielFisher too), add a ' ' at the end of your final printf() call as it may be required by your particular implementation or otherwise the program's behavior might be undefined (thanks to @KeithThompson and @AndreyT pointing this out in the comments):

 printf ("Why does this work, nc = %f
", nc);

这篇关于为什么程序不执行最终的 printf 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆