qs, jx笔试总结

来源:互联网 发布:nba数据统计 新浪 编辑:程序博客网 时间:2024/04/28 20:07

#include <stdio.h>
#include <assert.h>
#include <string.h> /* strlen, strcpy, strncpy */
#include <stdlib.h>

#define S(a) a*a

/* qs, jx笔试总结 */

int getsum(int n);
int *tfunc(int input);
void loopmove(char *pstr, int steps);

typedef union { // union 取其中的最大值, 不要看成struct :(
 int a[5];
 int b;
 char c;
} elem; // 5*4 = 20.

typedef struct {
 elem t;
 double data;
 char *p;
} node; // 20+8+4 = 32.

int main()
{
 {
  int x = 10, y = 2, z = 3;
  x /= S(z)/S(y);  // "/=" 的优先级是right to left. K&R P53.
  printf("%d/n", x);
  printf("-------------------/n");
 }
 
 {
  /*
  *  char 的2种特殊的表示方法:
  * '0hh' 表示八进制数, h from 0 to 7.
  * 'xhh' 表示十六进制数, h from 0 to f.
  */
  // char a = '/';  // 错误,'/' 是转义符.
  char b = '/x80';
  char c = '/077';
  char d = '/0xab'; // 非错误, 溢出警告, 取最低的 ‘a'
  char *e = "/0127";
  char f = 'abccdjkflas'; // 非错误, 溢出警告和超长, 取最低的 ‘s'
  printf("%d/n", c); // (111111) octal digit.
  printf("%c/n", d);
  printf("%c/n", f);
  printf("-------------------/n");
 }

 {
  int b = getsum(3);
  printf("%d/n", b);
  printf("-------------------/n");
 }

 {
  int b = sizeof(elem)+sizeof(node);
  printf("%d/n", b);
  printf("-------------------/n");
 }

 {
  char a = 256; // [-128, 127], 1 0000 0000, 截断为0000 0000
  int b = a;    // 0
  printf("%d/n", b++); // 0
  printf("-------------------/n");
 }
 
 {
  int b = 0x12345678;
  char *p = (char *)&b;
  int count = sizeof(int)/sizeof(char);
  int i;
  for (i=0; i<count; i++)
   printf("%x/n", *p++);  // Little-endian的CPU是低地址存操作数的低字节. 即78 56 34 12.
  printf("-------------------/n");
 }

 {
  int sum = 5050;
  unsigned int i;
  //for (i=100; i>=0; i--) // 不断的从0 跳变到最大值, 所以会是死循环. 变为i>0即可.
  for (i=100; i>0; i--)
  {
   sum -= i;
   //printf("%u ", i);
  }
  printf("%d/n", sum);
  printf("-------------------/n");
 }

 {
  char a[] = "abcdefghi";
  loopmove(a, 2);
  printf("%s/n", a);
  char b[] = "1234567890abcdefghi";
  loopmove(b, 9);
  printf("%s/n", b);
  printf("-------------------/n");
 }
 
 return 0;
}

/* 2+5+8+11 ..., get sum. */
int getsum(int n)
{
 assert(n > 0);
 int s = 0, t;
 while (n-- > 0)
 {
  s += 2+3*n;  
 }
 return s;
/*
 * 错误提示: 不要写成求一项.
 */
}

/* 将字符串循环右移n位, 如n=2时,从"abcdefghi" 到 "hiabcdefg". */
void loopmove(char *pstr, int steps)
{
 assert(pstr != NULL);
 int i;
 int n = steps;
 int len = strlen(pstr);
 
 if (n == len)
  return;
 if (n>len)
  n = n%len; 
 char *p = (char *)malloc(n+1);
 strcpy(p, pstr+len-n);
 for (i=len-n-1 ; i>=0; i--)
  pstr[i+n] = pstr[i];
 strncpy(pstr, p, n);
 free(p);
 p = NULL;
 return ;
}

原创粉丝点击