You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50 Scrabble实验:uppercase与compute_score函数编译错误排查

CS50 Scrabble 实验代码错误排查与修正

编译错误分析与修复

1. "未声明标识符" 错误

你代码里的int i;仅做声明未初始化,直接使用word[i]会触发编译器报错(实际为使用未初始化变量,可能被描述为未声明标识符)。此外,uppercase(word[i])调用完全错误:uppercase要求传入string类型参数,但你传的是单个char(word[i]),类型不匹配。

修复:

  • 在compute_score中先调用uppercase(word)将整个单词转大写,无需单独传单个字符;
  • 初始化循环变量i,通过循环遍历单词的每个字符。

2. 数组索引类型不匹配与越界错误

POINTS[word[i]]中,word[i]是char类型(比如'A'的ASCII值为65),而POINTS数组仅26个元素(索引0-25),直接用65作为索引会导致数组越界,同时编译器会提示char转int的类型问题。

修复:

  • 将大写后的字符减去'A',得到0-25的合法索引:word[i] - 'A',以此对应POINTS数组的正确位置。

3. uppercase函数的逻辑错误

你的uppercase仅打印转大写后的字符,并未实际修改原字符串,且返回类型为string却返回0(int类型),类型不匹配会导致未定义行为。

修复:

  • 修改uppercase为直接修改传入的字符串(CS50的string本质是char*),将每个字符转为大写,返回类型改为void,无需打印。

其他隐藏错误

  • compute_score原代码仅判断大写字母,未处理小写字母(调用uppercase后该问题解决);
  • 未处理非字母字符(如空格、数字),这类字符应不计分;
  • compute_score原代码最后返回0,未返回计算后的得分,导致永远返回0分。

修正后的完整代码

#include <ctype.h>
#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);
void uppercase(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 (score1 == score2)
    {
        printf("Tie!\n");
    }
    else
    {
        printf("Player 2 wins!\n");
    }
}

int compute_score(string word)
{
    // Convert word to uppercase first
    uppercase(word);
    
    int score = 0;
    for (int i = 0; word[i] != '\0'; i++)
    {
        // Check if current character is an uppercase letter
        if (word[i] >= 'A' && word[i] <= 'Z')
        {
            // Calculate index in POINTS array
            int index = word[i] - 'A';
            score += POINTS[index];
        }
        // Non-letter characters are ignored (no score)
    }
    return score;
}

void uppercase(string word)
{
    for (int i = 0; word[i] != '\0'; i++)
    {
        word[i] = toupper(word[i]);
    }
}

内容的提问来源于stack exchange,提问作者h.jr11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 15:49:57