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

CS50 Week2 Lab2问题:无法正确输出获胜者或平局结果

CS50 Week2 Lab2 程序问题修复指南

我的程序无法稳定正确输出获胜者或“平局”结果:例如输入Player1为“Oh,”、Player2为“oh,”时,程序输出“Player 2 Wins!”(本应是平局);交换输入后,会同时输出“Player 1 Wins!”和“tie!”。调试工具无法正常加载,作为刚学编程第二周的新手,急需解决问题的方向。

#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);

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);

    if (score1 > score2)
    {
        printf("Player 1 Wins!\n");
    }
    if (score1 < score2)
    {
        printf("Player 2 Wins!\n");
    }
    else
    {
        printf("Tie!\n");
    }
}

int compute_score(string word)
{
    int score = 0;
    int n = strlen(word);
    for (int i = 0; i < n; i++)
    {
       //if letter is uppercase
       if (isupper (word[i]))
       {
            POINTS[i] = word[i] - 65;
            score += POINTS[i];
       }
       //if letter is lowercase
       if (islower(word[i]))
       {
            POINTS[i] = word[i] - 97;
            score += POINTS[i];
       }
        //if character is not a letter
       else
       {
            i += 1;
       }
    }
     return score;
}

核心问题1:条件判断逻辑混乱

main函数里的两个独立if导致分支执行冲突:

  • 当score1 > score2时,第一个if输出“Player 1 Wins!”,第二个if(score1 < score2)不成立,会触发对应的else输出“Tie!”,所以会同时打印两个结果。
  • 修复:改成if-else if-else链式判断,确保只会执行其中一个分支:
if (score1 > score2)
{
    printf("Player 1 Wins!\n");
}
else if (score1 < score2)
{
    printf("Player 2 Wins!\n");
}
else
{
    printf("Tie!\n");
}

核心问题2:破坏全局分数数组POINTS

compute_score里错误修改了POINTS数组的原始值:

  • POINTS是预先定义的字母分数对照表(A对应1,B对应3...),但你把它当成临时变量存储字母的索引(比如'O'-65=14),第一次计算后POINTS数组被彻底篡改,第二次计算时用的是被破坏的数组,导致分数完全错误。
  • 修复:用临时变量存储字母索引,再去POINTS里取对应分数,不要修改原数组:
// 大写字母处理
if (isupper(word[i]))
{
    int index = word[i] - 'A'; // 用字符常量代替ASCII码,可读性更好
    score += POINTS[index];
}
// 小写字母处理,改成else if避免重复判断
else if (islower(word[i]))
{
    int index = word[i] - 'a';
    score += POINTS[index];
}

次要问题:多余的i += 1

for循环本身每次会自动执行i++,额外的i +=1会导致跳过下一个字符(比如连续两个非字母时,会跳过两个),直接删除这个分支里的i +=1即可,非字母字符不做处理,循环会自动推进。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:28:01