CS50x课程Bulbs程序故障:第三、四位灯泡恒亮
CS50x Bulbs程序二进制显示错误排查与解决
问题描述
- 开发目标:为CS50x课程实现Bulbs程序,功能是将输入字符串转换为二进制,用🟡(对应二进制1,表示亮)和⚫(对应二进制0,表示灭)在终端展示。
- 异常现象:测试输入数字"1"和"4"时,第三、四位灯泡始终亮起。例如输入"1",程序输出二进制
00110001(对应⚫⚫🟡🟡⚫⚫⚫🟡),但正确的二进制应为00000001。
问题解决
后续排查发现问题根源是对ASCII编码的理解偏差——输入的字符"1"对应的ASCII值是十进制49,而非数值1。修正逻辑后,程序已正常运行,提交代码的所有检查项均显示为绿色。
程序代码
#include <cs50.h> #include <stdio.h> #include <string.h> const int BITS_IN_BYTE = 8; void print_bulb(int bit); int main(void) { string text = get_string("Text to encrypt!: "); int bit; int n = strlen(text); int array[BITS_IN_BYTE] = {0, 0, 0, 0, 0, 0, 0, 0}; int count = 0; for ( int i = 0; i < n ; i++) { for (int j = 0, x = 7; j < 8 && x >= 0; j++, x--) { if (text[i] == 0) { array[x] = 0; } else if (text[i] == 1) { array[x] = 1; text[i] = 0; } else if (text[i] != 1 && text[i] != 0) { array[x] = text[i] % 2; text[i] = text[i]/2; //jak dojdzie do 1 to? } } for (int y = 0; y <= 7; y++) { print_bulb(array[y]); } printf("\n"); } } void print_bulb(int bit) { if (bit == 0) { // Dark emoji printf("\U000026AB"); } else if (bit == 1) { // Light emoji printf("\U0001F7E1"); } }
内容的提问来源于stack exchange,提问作者Rae
相关产品推荐
相关产品推荐

