Solution for Exercise 14-2

ex1402

#include <stdio.h>

int main()
{
    struct player
    {
        char name[32];
        int highscore;
        float hours;
    };
    struct player xbox;

    printf("Enter the player's name: ");
    scanf("%s",xbox.name);
    printf("Enter their high score: ");
    scanf("%d",&xbox.highscore);
    printf("Enter the hours played: ");
    scanf("%f",&xbox.hours);

    printf("Player %s has a high score of %d\n",
            xbox.name,xbox.highscore);
    printf("Player %s has played for %.2f hours\n",
            xbox.name,xbox.hours);

    return(0);
}

Output

Enter the player's name: Simon
Enter their high score: 100
Enter the hours played: 1280.5
Player Simon has a high score of 100
Player Simon has played for 1280.50 hours

Notes

* The key point with your solution is to add a float variable member to the player structure. The rest of the code can be written however you want to interpret it; I used two printf() statements, for example, to display the data, using the %.2f conversion character. Your solution need not match.

* You could also combine the structure's declaration with the structure variable declaration, as in:

This format is just a personal choice. I prefer to break up structure definitions and variable declarations. It makes the declaration easier to see, at least for my brain.