0

QUESTION

  1. When i am giving an input as only ? and only ! ===> everything is normal result is equals to TIE
  2. Player1 : ? ---- Player2 : !
  3. but when i give like Question? and Question! (? and !) ===> acts like d and f
  4. Player1 : Question? ---- Player2 :Question!
  5. Program understands Questiond and Questionf
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(score2 > score1)
    {
        printf("Player 2 wins!\n");
    }
    else
    {
        printf("Tie!\n");
    }
}


int compute_score(string word)
{

    char letters[strlen(word)];

    for(int a=0; a < strlen(word); a++)
    {
        letters[a] += word[a];
    }

    int totalscore = 0;
    int asciiValuesofLetters = 0;

    for(int j= 0; j < strlen(word); j++)
    {
        asciiValuesofLetters = (int)letters[j];

        if(asciiValuesofLetters >= 65 && asciiValuesofLetters <= 90 | asciiValuesofLetters >= 97 && asciiValuesofLetters <=122)
        {
            if(asciiValuesofLetters > 90)
            {

                totalscore += POINTS[asciiValuesofLetters-97];
            }
            else
            {
                totalscore += POINTS[asciiValuesofLetters-65];
            }
        }
        else
        {
            totalscore += 0;
        }
    }
    for(int a=0; a < strlen(word); a++)   //Cleaning inside of the array
    {
        letters[a] -= word[a];
    }
    return totalscore;
}
1

The problem is here: letters[a] += word[a];. The letters array is not initialized. Therefore it holds any values that may be in the memory assigned to it. The purpose of this loop is to set the value of letters to the value of word at the same index. Therefore the + is unnecessary, and is in fact causing the problem.

2
  • Thanks a lot man that solved the problem but actually i still don't understand what is the problem with that where did that d and f came from ? Jan 4 '21 at 17:07
  • It just so happens that the contents of memory at that location plus ? or ! evaluates to f and d. The result is unpredictable because the contents of the memory location depends on a lot of factors. Jan 4 '21 at 18:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .