gpt4 book ai didi

c - 一小段位的初始化错误 - 为什么错误地设置了最后两个变量的最高有效位?

转载 作者:行者123 更新时间:2023-11-30 15:18:34 25 4
gpt4 key购买 nike

我编写这个程序是为了练习按位运算。在下面的代码行中,我尝试将值逐位分配给三个 short 。然后我通过 bit_print() 函数打印它们。

        #include <stdio.h>
#include <limits.h>

void bit_print(short a)
{
int i;
int n = sizeof(short) * CHAR_BIT; /* in limits.h */
short mask = 1 << (n - 1); /* mask = 100...0 */

for (i = 1; i <= n; ++i) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}

int main(void){
short alice = 0, betty = 0, carol = 0;
int x;
char c;

printf("Put 16 bits for Alice: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
alice |= 1 << x;
else
alice |= 0 << x;
}
putchar('\n');

printf("Put 16 bits for Betty: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
betty |= 1 << x;
else
betty |= 0 << x;
}
putchar('\n');

printf("Put 16 bits for Carol: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
carol |= 1 << x;
else
carol |= 0 << x;
}
putchar('\n');

bit_print(alice);
putchar('\n');
bit_print(betty);
putchar('\n');
bit_print(carol);
putchar('\n');

return 0;
}

由于某种原因,如果我输入 1111111111111111 三次,执行程序我会得到以下输出:

Put 16 bits for Alice: 1111111111111111

Put 16 bits for Betty: 1111111111111111

Put 16 bits for Carol: 1111111111111111

11111111 11111111
01111111 11111111
10111111 11111111

正如您所看到的,最后两个变量 betty 和 carol 的最高有效位在不应该为零的地方有零。为什么?

最佳答案

使用 getchar() 时,您在输入末尾按下的换行符会被拾取,但您没有考虑到它。

您需要在每个循环末尾读取并丢弃换行符以解决此问题:

    #include <stdio.h>
#include <limits.h>

void bit_print(short a)
{
int i;
int n = sizeof(short) * CHAR_BIT; /* in limits.h */
short mask = 1 << (n - 1); /* mask = 100...0 */

for (i = 1; i <= n; ++i) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}

int main(void){
short alice = 0, betty = 0, carol = 0;
int x;
char c;

printf("Put 16 bits for Alice: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
alice |= 1 << x;
else
alice |= 0 << x;
}
putchar('\n');
getchar();

printf("Put 16 bits for Betty: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
betty |= 1 << x;
else
betty |= 0 << x;
}
putchar('\n');
getchar();

printf("Put 16 bits for Carol: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
carol |= 1 << x;
else
carol |= 0 << x;
}
putchar('\n');
getchar();

bit_print(alice);
putchar('\n');
bit_print(betty);
putchar('\n');
bit_print(carol);
putchar('\n');

return 0;
}

关于c - 一小段位的初始化错误 - 为什么错误地设置了最后两个变量的最高有效位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com