首页 > 解决方案 > CS50 - 实验 2:拼字游戏 - 错误:调用的对象类型“int [26]”不是函数或函数指针拼字游戏

问题描述

我一直在做这个代码;应该从两个不同的玩家那里取词,计算分数,同时使用 for 循环一次遍历每个角色。我已经重读了 1000 遍,但似乎没有帮助。

我在第 45 行和第 49 行收到此错误消息:

错误:调用的对象类型“int [26]”不是函数或函数指针拼字游戏

不要给我答案,只是给我一些指导。谢谢你。这是我的代码:

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

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

int compute_score(string word)
{
    //Compute and return store for string
    int score = 0;
    int l = strlen(word);

    for (int n = 0; n < l; n++)
    {
        if (isupper(word[n]))
        {
            score += POINTS(word[n] - 'A');
        }
        else if (islower(word[n]))
        {
            score += POINTS(word[n] - 'a');
        }
    }
    return score;
}

标签: ccs50

解决方案


就像编译器说的那样,POINTS是一个类型的数组int [26]。有问题的行是:

POINTS(word[n] - 'A')

那只是胡说八道,你不能使用这样的数组。编译器认为它看起来像一个函数调用(),因此出现了奇怪的编译器错误。您可能打算访问该数组,这将是:

POINTS[word[n] - 'A']

但你已经知道了,既然你猜对了word[n]……

一个提示是不要过于关注编译器错误所说的内容,而是关注它指向的行。编译器消息可能非常神秘,有些需要 C 资深人士才能理解。现在,只需将它们视为编译器在说“BAD:第 26 行”。


推荐阅读