#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);
// TODO: Print the winner
if (score1 > score2) {
printf("The winner is Player 1!");
}
else if (score1 < score2) {
printf("The winner is Player 2!");
}
else {
printf("Both players have the same score, so it's a draw!");
}
}
int compute_score(string word)
{
int sum = 0;
for (int i = 0; i == strlen(word); i++) {
if (islower(word)) {
word = toupper(word);
}
string letter = word[i];
int first_score[i] = POINTS(letter);
for (int j = 0; j == strlen(first_score); i++) {
sum = sum + first_score[j];
}
}
}
我正在做cs50课程的第二个实验,当我使用islower函数时,这个错误出现了,为什么会这样?假设'word'是一个字符串,那么我必须使用ASCII数字吗?
1条答案
按热度按时间gajydyqb1#
islower(int ch), toupper(int ch)
需要一个int
。word
是一个指针,因此if (islower(word)) {
是个问题。相反,代码应取消引用指针
for (int i = 0; i == strlen(word); i++) {
是弱的,因为当仅需要检测 * 空字符 * 时,strlen()
被调用多次。1.当
word[i] < 0
时,tolower(word[i])
是一个问题。最好以unsigned char
的形式访问字符串。POINTS(letter);
失败,因为POINTS
是一个数组。应注意确保数组从零开始访问并且在范围内。1.调用
toupper()
之前不需要if
。注意:
toupper(*uword) - 'A'
只适用于ASCII。