码迷,mamicode.com
首页 > 其他好文 > 详细

C puzzles详解【34-37题】

时间:2014-09-24 00:21:05      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   strong   for   div   

第三十四题

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题】

标签:style   blog   color   io   os   ar   strong   for   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!