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

如何通过循环简化C语言单词计分程序的代码?

优化方案:合并循环+简化代码

核心问题解决:合并大小写处理循环

你完全可以把两个循环合并成一个,核心思路是统一将字母转为小写(或大写)后计算分值,不用分两次遍历字符串。另外原代码里的i <= len循环条件存在多余遍历(字符串结束符'\0'不需要处理),也可以一并优化。

优化后的完整代码

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

// 字母分值计算函数声明
int compute_score(string word);

int main(void)
{
    // 获取玩家输入
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    // 计算得分
    int score1 = compute_score(word1);
    int score2 = compute_score(word2);

    // 输出胜负结果
    if (score1 > score2)
        printf("Player 1 wins!\n");
    else if (score1 < score2)
        printf("Player 2 wins!\n");
    else
        printf("Tie!\n");
}

int compute_score(string word)
{
    // A-Z对应的分值(索引0对应A,1对应B,以此类推)
    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 total = 0;

    // 遍历字符串直到结束符,无需提前计算长度
    for (int i = 0; word[i] != '\0'; i++)
    {
        char c = word[i];
        // 仅处理字母字符
        if (isalpha(c))
        {
            // 转小写后计算索引,统一匹配points数组
            int idx = tolower(c) - 'a';
            total += points[idx];
        }
    }

    return total;
}

关键改动说明

  • 合并循环:单个循环遍历所有字符,通过tolower()将大写字母转为小写,统一计算数组索引,避免重复遍历字符串。
  • 简化逻辑:去掉多余的totall、len等变量,直接通过word[i] != '\0'判断循环结束,省去strlen调用。
  • 可读性提升:用isalpha()判断字母(比硬编码ASCII值更直观),用'a'替代97这类魔法数字,代码更易维护。
  • 修复冗余遍历:原代码i <= len会遍历到字符串结束符,优化后仅处理有效字符。

进一步精简代码(可选)

如果追求极致简洁,compute_score可以写成更紧凑的形式(可读性略有下降):

int compute_score(string word)
{
    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 total = 0;
    for (int i=0; word[i]; i++)
        if (isalpha(word[i])) total += points[tolower(word[i])-'a'];
    return total;
}

内容的提问来源于stack exchange,提问作者Mo salah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:10:33