0
#include <stdio.h>

#define NUMVALS 6
#define SIZE 5
#define MAX 31

int main () {

   int vals = 0;

   short curVal, idx = 0;


   for(; idx < NUMVALS; ++idx) {
      scanf("%d", &curVal);

      vals = (vals << SIZE) | curVal;
   }

   printf("%d", vals | curVal);

   return 0;
}

这是我正在处理的一些代码。它应该存储 6 个整数,每个整数都在 0 到 31 的范围内,因此每个整数都有 5 位的空间。由于某种原因,它不起作用。当我在循环中对 vals 进行赋值时,它似乎只是将读入的当前值存储到 vals 中。你知道可能出了什么问题吗?

4

3 回答 3

4

一个体面的编译器会告诉你:

warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘short int *’
     scanf("%d", &curVal);

您需要使用%hd来扫描short,或者(在这种情况下更好)将您的变量更改为int.

如果您使用的是 GCC,请添加-Wall -Wextra -Werror到您的编译命令中。它会为你抓住这个。

于 2015-01-23T08:20:18.277 回答
1

首先更改valsto的类型long int,因此它将能够存储至少 30 位和 to 的类型curValint匹配 scanf 调用。

Then make sure you only assing 5 bits to vals:

vals = (vals << SIZE) | ( curVal | 0x1F );

And when you print the last value, use the and bitwise operator, since you only want to keep the least significant 5 bits.

printf("%ld", vals & 0x1F );
于 2015-01-23T08:25:04.233 回答
-1

Mr. Alpha, if you want to store 6 values the for loop must run for 6 times.so you need <= in condition as idx<=NUM.... And one more thing is you are not storing at any place,through out the program.

于 2015-01-23T09:35:59.830 回答