【发布时间】:2021-06-30 17:00:08
【问题描述】:
我为 cs50 编写了代码。我的任务是创建一个拼字游戏。小写字母一切正常,但是当我尝试使用大写字母时,计算机返回给我的值总是相同的 0。我试图自己修复它,但我只会让它变得更糟。如果有人能告诉我怎么做,我将不胜感激。
// 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);
printf("Score for Player 1: %i\n", score1);
printf("Score for Player 2: %i\n", score2);
// 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 word)
{
// Compute and return score for string
int compute_score = 0;
int numb;
for (int i = 0, n = strlen(word); i < n; i++)
{
if(isupper(word[i]))
{
numb = word[i] - 65;
numb = POINTS[numb];
}
if(islower(word[i]))
{
numb = word[i] - 97;
numb = POINTS[numb];
}
else
{
numb = 0;
}
compute_score += numb;
}
return compute_score;
}
【问题讨论】:
-
是的,您的 compute_score 函数对大写字母给出 0 分。仔细阅读,看看你是否能找出原因。
-
您定义了
int main(void),然后又定义了void main(void)。你不能定义main(或任何函数)两次,void main(void)不是main的有效原型。 -
不要硬编码像 65 和 97 这样的值。改写
'A'和'a'。尽管您的代码不太可能在具有不同编码的机器上运行(它曾经更常见),但它更更易于阅读。