CS50 Scrabbles类游戏C语言代码优化与逻辑校验咨询
原代码存在的核心错误
- 函数逻辑完全偏离需求:
compute_score没有实现“遍历字符、匹配字母对应分值、累加总分”的核心逻辑- 循环内每次迭代都把
score1重置为0,完全无法累加分数 - 存在越界访问风险:循环到最后一个字符时,
word[i+1]会访问字符串结束符之外的未定义内存 - 第一个return语句之后的所有代码完全不会被执行,属于无效冗余代码
- 前面手动给A-Z赋值26个char变量的操作完全没被使用,纯冗余
- 循环内每次迭代都把
- 主函数分支缺失:两个玩家得分相同时,现有逻辑会直接判定玩家2获胜,不符合Scrabble规则
- 输出格式不规范:printf语句末尾没有加换行符,输出内容会和后续命令行提示符粘连
优化实现方案
- 删除所有无意义的手动字母赋值代码,利用字符的ASCII码特性:大写字母'A'到'Z'的连续编码和POINTS数组的下标一一对应,直接通过
字符 - 'A'就能得到对应分值的下标,不用手动维护映射关系 - 补充大小写兼容、非字母字符(标点、空格等)的分值处理逻辑:只有字母参与计分,非字母字符得0分直接跳过
- 补全平局判断的分支
- 得分变量在循环外初始化,避免每次迭代重置总分
修正后的完整可运行代码
#include <cs50.h> #include <stdio.h> #include <string.h> // Points assigned to each letter of the alphabet int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10}; int compute_score(string word); int main(void) { // Get input words from both players string word1 = get_string("Player 1: "); string word2 = get_string("Player 2: "); // Score both words int score1 = compute_score(word1); int score2 = compute_score(word2); // Print the winner if (score1 > score2) { printf("Player 1 wins!\n"); } else if (score2 > score1) { printf("Player 2 wins!\n"); } else { printf("Tie!\n"); } } int compute_score(string word) { int total_score = 0; int word_len = strlen(word); for (int i = 0; i < word_len; i++) { // 处理大写字母 if (word[i] >= 'A' && word[i] <= 'Z') { int point_idx = word[i] - 'A'; total_score += POINTS[point_idx]; } // 处理小写字母 else if (word[i] >= 'a' && word[i] <= 'z') { int point_idx = word[i] - 'a'; total_score += POINTS[point_idx]; } // 非字母字符不计分,直接跳过 } return total_score; }
内容的提问来源于stack exchange,提问作者Coding_For_Fun
相关产品推荐
相关产品推荐

