首页 > 其他 > 详细

C puzzles详解【34-37题】

时间:2014-09-23 22:05:36      阅读:216      评论:0      收藏:0      [点我收藏+]

第三十四题

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesnt 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-- )

 

第三十五题

Whats 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\n", 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\n",i);
      return 0;
  }

题目解答:

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

C puzzles详解【34-37题】

原文:http://www.cnblogs.com/tanghuimin0713/p/3989380.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!