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

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

问题描述

我找不到为什么程序控制没有到达for循环之后的第三个printf。

为什么不打印第三个 printf

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

下面是程序和输出:

  main()
{
double nc;

printf(为什么这个工作,nc =%f \ n,nc);
for(nc = 0; getchar()!= EOF; ++ nc)
{
printf(%.0f\\\
,nc);

printf(为什么这个工作,nc =%f,nc);



$ b $ p
$ b $输出是:

 为什么这么做,nc = 0.000000 
test
0
1
2
3
4


解决方案

暂停程序?一旦 EOF getchar()检测为输入, -loop的 code $。
$ b

EOF Control-Z ^ Z )和 Control-D ^ D )在Linux / Unix下。一旦我进入这个循环,循环结束,我得到最后的 printf()来显示它的输出。



最后一个注释(如@DanielFisher也提到),在最后的 printf()结尾添加一个'\\\
'
c $ c>调用,因为它可能是您的特定实现需要的,否则程序的行为可能是不确定的(感谢@KeithThompson和@AndreyT在注释中指出了这一点):

  printf(为什么这个工作,nc =%f \ n,nc); 


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

Why won't the third printf print?

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

Here is the program and output:

main()
{
    double nc;

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

The output is:

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

解决方案

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

As a final note (as mentioned by @DanielFisher too), add a '\n' 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\n", nc);

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

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