【发布时间】:2020-06-01 11:26:18
【问题描述】:
我编写了一个程序,它可以在没有位运算符的情况下检查 32 位整数的奇偶校验。除了声明之外,我也不能使用] 符号。我的程序已经很好了,但我不知道如何在没有[ 符号的情况下让它工作。我尝试了很多方法,但我的程序不想编译。这是我的程序:
#ifndef bit_set
#define bit_set
struct bit{
unsigned b0 : 1;
unsigned b1 : 1;
unsigned b2 : 1;
unsigned b3 : 1;
unsigned b4 : 1;
unsigned b5 : 1;
unsigned b6 : 1;
unsigned b7 : 1;
};
union bit_set
{
unsigned int x;
struct bit foo[4];
}word;
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"
int main(void) {
printf("Input number: ");
if (scanf("%u", &word.x) == 0) {
printf("Incorrect input");
return 1;
}
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += word.foo[i].b0 + word.foo[i].b1 + word.foo[i].b2 + word.foo[i].b3 + word.foo[i].b4 + word.foo[i].b5 + word.foo[i].b6 + word.foo[i].b7;
}
sum % 2 ? printf("NO") : printf("YES");
return 0;
}
【问题讨论】:
-
欢迎来到 SO。您可能还记得
a[i]与*(a+i)相同。 -
我尝试了例如
word.*(foo+i).b0,但它不会编译。除非我理解错了,而你的意思是别的。 -
@DariuszMajcherczyk 优先级:
.的运算符优先级高于*,因此您必须编写(*(foo+i)).b0。这反过来又是可怕的代码,除了如何成为一个糟糕的 C 程序员之外,没有什么可以从这个练习中学到的。 -
也许它应该学习优先级,我不知道。这个
(*(foo+i)).b0也不起作用。 -
你试过
(*(word.foo+i).b0吗?