首页 > 解决方案 > cs50 拼字游戏:无论输入什么,总是打印相同的答案

问题描述

我需要为 cs50 课程编写一个拼字游戏。现在我有这个代码,但问题是起初它总是打印“领带!” 现在它总是打印出“玩家 2 获胜!” 无论我输入什么。我认为我的错误是在 for 循环中,你将字母分配给数字,但我真的不知道如何修复它。有人可能知道怎么做吗?

// 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 word1);
int compute_scores(string word2);

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 = (int) compute_score;
    int score2 = (int) compute_scores;

    // Print the winner
    if (score1 == score2)
    {
        printf("Tie! \n");
    }
    if (score1 < score2)
    {
        printf("Player 2 wins! \n");
    }
    if (score1 > score2)
    {
        printf("Player 1 wins! \n");
    }
}

int compute_score(string word1)
{
    // Compute and return score for string
    int compute_score = 0;
    int numb;
    for (int i = 0, n = strlen(word1); i < n; i++)
    {
        if(isupper(word1[i]))
        {
            numb = word1[i] - 65;
            numb = POINTS[numb];
        }
        if(islower(word1[i]))
        {
            numb = word1[i] - 97;
            numb = POINTS[numb];
        }
        else
        {
             numb = 0;
        }
    }
    compute_score = numb;
    return compute_score;
}

int compute_scores(string word2)
{
    // Compute and return score for string
    int compute_scores = 0;
    int numb;
    for (int i = 0, n = strlen(word2); i < n; i++)
    {
        if(isupper(word2[i]))
        {
            numb = word2[i] - 65;
            numb = POINTS[numb];
        }
        if(islower(word2[i]))
        {
            numb = word2[i] - 97;
            numb = POINTS[numb];
        }
        else
        {
            numb = 0;
        }
    }
    compute_scores = numb;
    return compute_scores;
}

标签: ccs50scrabble

解决方案


当您是初学者时,几乎不存在需要使用演员表的情况。或者在极少数情况下您需要一个,您需要知道自己在做什么。

int score1 = (int) compute_score;将函数本身的无符号地址转换为可能不适合的有符号整数。那是胡说八道。您需要调用该函数并将结果存储在int. 任何地方都没有铸造。

我建议您阅读您最喜欢的 C 书籍中的函数。我还建议放弃 CS-50,因为这是一门糟糕的课程,教的是糟糕的做法。它在 C 程序员中的名声很差。


推荐阅读