今天在CSDN上看到一个有意思的小题目,题目如下:

int main(){
    if(/*在此填入一个语句*/) printf("Hello");
    else printf(" World!");
}

要求填入一个语句,能够使上面的程序顺利打印出helloworld。

这个题目应该说一点都不难,解法也有很多种。首先,最笨的解法当然是下面这个:

int main(){
        if (!printf("hello"))   
                printf("hello");
        else
                printf("world!");
}

这个解法一看就没有什么技术含量,也应该不是面试者所需要的。那么,有没有更好的办法呢?

一般情况下,括号里的条件要么成立,要么不成立,所以一次执行没有办法两个分支都跑到,那么就应该需要两次执行。想到两次执行,在没有循环的条件下,自然想到了递归多进程

这个题目用递归怎么实现,我暂时还没想出来。但是用多进程来实现,确是一件很有意思的事情:

int main(){
        if (fork() ) //产生一个子进程打印world 
                printf("hello");
        else
                printf("world!");
}

想一想,这样子行了么?

答案是不行!因为fork之后,子进程和父进程不一定谁先执行,有可能打印出helloworld!,也有可能打印出world!hello。既然这样,那就想办法让打印world的进程先停下来:

int main(){
        if (fork() || sleep(1)) //产生一个子进程,睡眠并打印world  
                printf("hello");
        else
                printf("world!");
}

这样可以顺利打印出helloworld来了。但是,还有一个问题,hello打印完后会停顿一下再打印world。把时间设置小一点是个好办法,但有没有更好的办法了呢?让父进程等待子进程如何?看下面的代码:

int main(){
        if ( !fork() || (!wait()) ) //子进程打印hello,父进程等待子进程结束  
                printf("hello");
        else
                printf("world!");//子进程结束后,父进程打印world!
}

我暂时就能想到这几种方法了,当然还可以用嵌入式汇编之类的。还有没有更好的方法呢?用递归怎么能够实现?希望大家能想一想!

anyShare分享到:
Tagged with:
 

11 Responses to “一个C语言的填空题目,Helloworld”

  1. lixianmin says:

    其实还有一个办法,让函数在if()语句内直接打印完整的"hello world",然后接着return返回,c代码示例如下:

    C/C++ code

    int main()
    {
    if (printf("hello world")> 0) return 0; else if (true)
    printf("hello");
    else
    printf("world");

    return 0;
    }

  2. remychan says:

    thanks for posting. well done!

  3. anonymous says:

    fork wait 漂亮啊哈

  4. flankechen says:

    递归的方法,有点绕~~,
    int main()
    {
    static int i = 0 ;
    if( i++==0 ? main(): 1)
    printf("Hello,");
    else
    printf("World\n");

    return 0 ;
    }

  5. yql says:

    if( fork() || sleep(1) )
    printf("hello");
    else
    printf("world\n");
    有点不理解,条件写的是如果是子进程就睡一秒吧,如果是父进程就不理sleep()。那这个条件跟
    if(fork()>0)
    printf("hello");
    else
    printf("world");
    是一个效果吧
    但是不是说父进程和子进程的执行顺序不一定的么

  6. niesongsong says:

    你可以使用vfork

    int main(){
    if (vfork() ) //产生一个子进程打印world
    printf("hello");
    else
    printf("world!");
    }

Leave a Reply

Note: Commenter is allowed to use '@User+blank' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC '(exclude ') will automatically send your comment to ABC. Using '@all ' to notify all previous commenters. Be sure that the value of User should exactly match with commenter's name (case sensitive).