• C puzzles详解【31-33题】


    第三十一题

    The following is a simple C program to read and print an integer. But it is not working properly. What is(are) the mistake(s)? 
      #include <stdio.h>
      int main()
      {
          int n;
          printf("Enter a number:
    ");
          scanf("%d
    ",n);
    
          printf("You entered %d 
    ",n);
          return 0;
      }

    题目讲解:

    运行后发生段错。

    问题出在这一行

    scanf("%d
    ",n);

    首先,scanf的第二个参数应该是个地址。若是从标准输入读入数据到变量n中,这一行应该改成

    scanf("%d
    ",&n);

    再次编译运行,发现要输入一个数值后回车,程序并不会返回,再次输入一个数值后才会返回,n的值是第一次输入的值。

    参考http://book.51cto.com/art/200901/106938.htm

    ‘ ’在scanf格式中不表示等待换行符,而是读取并放弃连续的空白字符,因此“%d ”中的’ ’会让scanf读到非空白字符为止。要使用户输入一个数据回车后程序立马返回,去掉scanf中的’ ’即可。

    scanf("%d",&n);

    第三十二题

    The following is a simple C program which tries to multiply an integer by 5 using the bitwise operations. But it doesn't do so. Explain the reason for the wrong behaviour of the program. 
      #include <stdio.h>
      #define PrintInt(expr) printf("%s : %d
    ",#expr,(expr))
      int FiveTimes(int a)
      {
          int t;
          t = a<<2 + a;
          return t;
      }
    
      int main()
      {
          int a = 1, b = 2,c = 3;
          PrintInt(FiveTimes(a));
          PrintInt(FiveTimes(b));
          PrintInt(FiveTimes(c));
          return 0;
      }

    题目讲解:

    函数FiveTimes中,

    t = a<<2 + a;

    ‘+’的优先级高于’<<’,应改成

    t = (a<<2) + a;

    第三十三题

    Is the following a valid C program? 
      #include <stdio.h>
      #define PrintInt(expr) printf("%s : %d
    ",#expr,(expr))
      int max(int x, int y)
      {
          (x > y) ? return x : return y;
      }
    
      int main()
      {
          int a = 10, b = 20;
          PrintInt(a);
          PrintInt(b);
          PrintInt(max(a,b));
      }

    题目讲解:

    编译有错误:

    test.c: In function ‘max’
    test.c:5: error: expected expression before ‘return

    (x > y) ? return x : return y;

    改成

    return (x > y) ? x : y;
  • 相关阅读:
    内功心法-代理模式
    java.lang.NumberFormatException: multiple points
    MarkDown语法-使用博客园的markDown编辑
    MarkDown语法
    linux下安装tomcat——service tomcat does not support chkconfig
    关于git&github的操作
    activeMQ 本地测试
    spring AOP 的坑~
    js高级面试题
    js的内存管理
  • 原文地址:https://www.cnblogs.com/tanghuimin0713/p/3989364.html
Copyright © 2020-2023  润新知