zoukankan      html  css  js  c++  java
  • C puzzles详解【34-37题】

    第三十四题

    The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work. 
      #include <stdio.h>
      int main()
      {
          int i;
          int n = 20;
          for( i = 0; i < n; i-- )
              printf("-");
          return 0;
      }
    Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three.

    题目讲解:

    for( i = 0; i < n; i-- )

    改成

    for( i = 0; i < n; n-- )

    第三十五题

    What's the mistake in the following code? 
      #include <stdio.h>
      int main()
      {
          int* ptr1,ptr2;
          ptr1 = malloc(sizeof(int));
          ptr2 = ptr1;
          *ptr2 = 10;
          return 0;
      }

    题目讲解:

    int* ptr1,ptr2;

    ptr1是指针,ptr2不是指针

    改成

    int *ptr1,*ptr2;

    第三十六题

    What is the output of the following program? 
      #include <stdio.h>
      int main()
      {
          int cnt = 5, a;
    
          do {
              a /= cnt;
          } while (cnt --);
    
          printf ("%d
    ", a);
          return 0;
      }

    题目讲解:

    cnt减到最后为0,运行后有“trap divide error”“floating point exception”的错误。

    第三十七题

    What is the output of the following program? 
      #include <stdio.h>
      int main()
      {
          int i = 6;
          if( ((++i < 7) && ( i++/6)) || (++i <= 9))
              ;
          printf("%d
    ",i);
          return 0;
      }

    题目解答:

    i的值为8。先执行(++i < 7),此表达式的值为0,i=7,由于逻辑运算符的短路处理,(i++/6)跳过执行,
    ((++i < 7) && ( i++/6))值为0,接着执行(++i <= 9),i的值最终为8。

  • 相关阅读:
    Leaflet_创建地图(官网示例,可以直接运行)(2017-10-20)
    三范式_数据库
    JavaScript_几种继承方式(2017-07-04)
    JavaScript_几种创建对象(2017-07-04)
    JavaScript_作用域(2017-03-16)
    JavaScript_原型和继承(2017-03-15)
    onBlur事件与onfocus事件(js)
    Bootstrap新手常见问题
    bootstrap小结
    Bootstrap 字形图标(Glyphicons)
  • 原文地址:https://www.cnblogs.com/tanghuimin0713/p/3989380.html
Copyright © 2011-2022 走看看