C语言几道题

    • C语言刷题
        • 1打印1100的质数
        • 2实现类似atoi函数
        • 3统计一个unsigned short类型的值中有多少位为1
        • 4将unsigned int val中val的值取出每个字节并累加求和sum
        • 5测量机器大小端

C语言刷题

1、打印1~100的质数

void Num()
{
    int i = 0, j = 0;
    for (i = 1; i <= 100; ++i)
    {
        for (j = 2; j <= i; ++j)
        {
            if(i % j == 0)  
            {
                break;
            }
        }
        if (j == i)
        {
            printf("%d\n", i);
        }
    }
}

2、实现类似atoi函数

void myatoi()
{
  char *str = "123456";                                                   
  int n = strlen(str);
  int m;
  int i = 0;
  int sum = 0;
  for (i = 0; i < strlen(str); ++i)
  {
    m = pow(10, --n);
    sum += (str[i] - '0') * m;
  }
  printf("%d\n", sum);
 }

3、统计一个unsigned short类型的值中有多少位为1

void To2()
{
    unsigned short m = 85;
    int a = m , b;
    int num = 0;
    while(1)
    {

        b = a % 2;
        a = a / 2;
        if (b == 1)
        {
            num++ ;
        }
        printf("%d %d\n", a, b);
        if(a == 0)
        {
            break;
        }
    }
    printf("%d\n", num);
}

4、将unsigned int val中val的值取出每个字节并累加求和sum

unsigned int sum(unsigned int val)
{
    char *m = (char *)&val;
    printf("%x\n", m[0]+m[1]+m[2]+m[3]);
}

5、测量机器大小端

//方法1:
int HostOrder()//判断字节序
{
    int p = 0x1234;
    char m = ((char *)&p)[0];
    if (0x34 == m)
    {
        printf("小端\n");
        return 0;//little
    }
    else
    {
        printf("大端\n");
        return 1;//big
    }
}
//方法2:
union num {
    int a;
    char b;
}test;
int main()
{
    test.a = 0x123456;
    if(test.b == 56)
    {
        printf("小端\n");
    }
    else
    {
        printf("大端\n");
    }
    return 1;
}

你可能感兴趣的:(Linux)