花了很长时间才写出来,其实不难,注意数组的位置。
参考代码如下:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int main(void) { int n; unsigned int a; scanf("%u %d", &a, &n); //将a用32位的二进制模式表示的各位数存放在一个数组中 int bits[32] = { 0 }; int bitsindex = 31; int i = 32; while (i > 0) { bits[bitsindex--] = a % 2; a = a / 2; i--; } /* for (i = 0; i < 32; i++) { printf("%d", bits[i]); } printf("\n"); */ //用一个临时数组存放要移位的数,并将原数组中的对应位置置为0 int tmp[n]; for (i = 0; i < n; i++) { tmp[i] = bits[31 - n + 1 + i]; bits[31 - n + 1 + i] = 0; } //然后将这个临时数组赋给原数组的前n位 for (i = 0; i < n; i++) { bits[i] = tmp[i]; } unsigned int res = 0; for (i = 31; i >= 0; i--) { res += bits[i] * pow(2, 31 - i); } printf("%u\n", res); return 0; }
0.0分
1 人评分