我對編程很陌生,我正在做 CS50,在這個拼字游戲程式中我遇到了麻煩,因為我無法弄清楚我正在犯哪個分段錯誤。可能是我的索引在我的陣列之外。如果您能找到問題并向我解釋,我將不勝感激。
#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);
if (score1 > score2)
{
printf("Player 1 wins!\n");
}
else if (score1 == score2)
{
printf("Tie!\n");
}
else
{
printf("Player 2 wins!\n");
}
// TODO: Print the winner
}
int compute_score(string word)
{
int number;
int sum1=0;
for (int i = 0; i<strlen(word); i )
{
if (isupper(word))
{
number = POINTS[word[i]-'A'];
}
else if (word[i] < 97 || word[i]>122 || word[i]<65 || word[i]>90)
{
number = 0;
}
else
{
number = POINTS[word[i] - 'a'];
}
sum1 = sum1 number;
}
return sum1;
// Assign points to letters
// read the letters in the word
// covert the letters into scores and add
// TODO: Compute and return score for string
}
uj5u.com熱心網友回復:
if 陳述句中至少有這個條件
if (isupper(word))
是不正確的。你必須寫
if (isupper( ( unsigned char )word[i]))
此 if 陳述句中的條件
else if (word[i] < 97 || word[i]>122 || word[i]<65 || word[i]>90)
沒有意義。對于初學者來說,不要使用像 97 這樣的幻數。條件看起來像
else if ( !( ( word[i] >= 'a' && word[i] <= 'z' ) || ( word[i] >= 'A' && word[i] <= 'Z' ) ) )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482609.html
