#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");
}
if (score1 < score2)
{
printf("Player 2 Wins!\n");
}
else
{
printf("Tie!\n");
}
}
int compute_score(string word)
{
int score = 0;
int n = strlen(word);
for (int i = 0; i < n; i++)
{
//if letter is uppercase
if (isupper (word[i]))
{
POINTS[i] = word[i] - 65;
score += POINTS[i];
}
//if letter is lowercase
if (islower(word[i]))
{
POINTS[i] = word[i] - 97;
score += POINTS[i];
}
//if character is not a letter
else
{
i += 1;
}
}
return score;
}//例如,当我为命令行中的第一个玩家输入“噢”以进行测试时,为第二个玩家输入“哦”--它会打印“牌手两胜!”(应该是一条领带)。当我切换时,它会打印“玩家1胜!”还有“平手”我在如何解决这个问题上束手无策。不幸的是,我的调试并没有正确地加载到我的计算机上,因为我正在尝试通过并解决这个问题。任何方向都将不胜感激。
这是我第二个星期试着理解编程,我知道这会很艰难,我还没有准备好乘坐这趟陡峭的旅程!
发布于 2022-08-31 20:07:30
在函数compute_score中,您正在更改数组POINTS
POINTS[i] = word[i] - 65;
POINTS[i] = word[i] - 97;因此,最好用限定符const声明数组。
// Points assigned to each letter of the alphabet
const 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};宣布它为全球是没有什么意义的。在函数compute_score中移动数组声明。
此外,您使用的索引i也不正确。
score += POINTS[i];还有这句话
else
{
i += 1;
}是多余的而且是错误的。
该函数的外观如下所示
int compute_score( string word )
{
// Points assigned to each letter of the alphabet
static const 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};
const size_t N = sizeof( POINTS ) / sizeof( *POINTS );
int score = 0;
for ( ; *word; ++word )
{
//if letter is uppercase
if ( isupper( ( unsigned char )*word ) )
{
size_t i = *word - 'A';
if ( i < N ) score += POINTS[i];
}
//if letter is lowercase
else if ( islower( ( unsigned char )*word ) )
{
size_t i = *word - 'a';
if ( i < N ) score += POINTS[i];
}
}
return score;
}另外,总的来说,你必须写
if (score1 > score2)
{
printf("Player 1 Wins!\n");
}
else if (score1 < score2)
{
printf("Player 2 Wins!\n");
}
else
{
printf("Tie!\n");
}https://stackoverflow.com/questions/73560683
复制相似问题