CS50实验二:调用islower函数出现类型转换错误原因咨询
问题原因与解决方法
1. islower报错的直接原因
islower函数要求传入单个字符的整数值(实际是unsigned char转换为int,避免字符值为负的异常),但你传入的是整个string类型的word(CS50中string本质是char*,即字符指针),类型不匹配导致报错:把指针强制转换为更小的int类型。
你不需要手动转ASCII数值,直接传入单个字符即可——C语言中字符本身就是以ASCII值存储的。
2. 代码中的其他关键错误与修正
你的compute_score函数还有多处逻辑和语法问题,逐一修正:
错误1:循环条件错误
原代码for (int i = 0; i == strlen(word); i++)的条件i == strlen(word)会让循环直接跳过,应改为i < strlen(word),才能遍历字符串的每个字符。
错误2:islower和toupper的误用
这两个函数仅处理单个字符,不是整个字符串。正确写法是取当前字符word[i],判断是否为小写后转换为大写(无需修改原字符串,用临时变量存储即可)。
错误3:字符转数组索引逻辑错误
要获取字符对应的POINTS数组索引,需用大写字符减去'A':比如'A' - 'A' = 0对应POINTS[0],'B' - 'A' = 1对应POINTS[1],以此类推。
错误4:冗余的数组与循环
原代码中的first_score数组完全多余,直接通过字符计算索引后取POINTS的值累加即可。
错误5:函数缺少返回值
compute_score声明返回int,但未返回计算结果,会导致未定义行为,必须在函数末尾返回累加的分数sum。
修正后的完整代码
#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("The winner is Player 1!\n"); } else if (score1 < score2) { printf("The winner is Player 2!\n"); } else { printf("Both players have the same score, so it's a draw!\n"); } } int compute_score(string word) { int sum = 0; int length = strlen(word); // 提前计算长度,避免循环中重复调用影响效率 for (int i = 0; i < length; i++) { char c = word[i]; // 只处理字母字符,非字母不计分 if (islower(c)) { c = toupper(c); } if (c >= 'A' && c <= 'Z') { int index = c - 'A'; sum += POINTS[index]; } } return sum; // 返回计算的分数 }
关键说明
- 处理字符时,先转大写再判断是否为字母,过滤空格、数字等非字母字符(这些字符不计分)。
- 提前计算字符串长度,避免循环中重复调用
strlen,提升运行效率。
内容的提问来源于stack exchange,提问作者user20357700
相关产品推荐
相关产品推荐

