观察ASCII表,发现大写字母减去一个常量(65)可以一一对应POINTS列表的值,所以我们可以利用这个特点,有
- 遍历输入的字符串
- 将每个字符串的字母进行大写
- 定义一个变量值可以用来储存 每个大写过的字母对应的ASCII表的十进制值减去65的值,利用for循环累加
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
const int N = 65; //利用ASCII表减去65就是字母对应的POINTS的值
// 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);
// TODO: Print the winner
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)
{
// TODO: Compute and return score for string
int sum = 0;
for (int i = 0, n = strlen(word); i < n; i++)
{
if ((word[i] >= 'a' && word[i] <= 'z') || (word[i] >= 'A' && word[i] <= 'Z'))
{
word[i] = toupper(word[i]);
sum += POINTS[(word[i]) - N];
// printf("%i\n",(word[i])-N);
}
}
return sum;
}