skip to Main Content

Sorry for the basic question, I just started learning C.

This is the output I’m trying to get:
https://i.stack.imgur.com/t6D30.png

This is what I’m currently getting:
https://i.stack.imgur.com/0yoSQ.png

How do I get rid of the extra three zeros at the end of my Batting Average?

My code:

#include <string.h>

//structure
struct Stats {
    char player [20];
    double bat_avg;
    unsigned int hr;
    unsigned int rbi;
};

//function prototypes
void printHeader();

//begin of main
int main(void)
{
    int return_value = 0;
    struct Stats player_1, player_2, player_3;

    //player 1
    strcpy(player_1.player, " Kurt");
    player_1.bat_avg = 0.350;
    player_1.hr = 40;
    player_1.rbi = 123;

    //player 2
    strcpy(player_2.player, " Jenny");
    player_2.bat_avg = 0.321;
    player_2.hr = 4;
    player_2.rbi = 56;

    //player 3
    strcpy(player_3.player, " Amanda");
    player_3.bat_avg = 0.281;
    player_3.hr = 15;
    player_3.rbi = 76;

    //print the heading
    printHeader();

    //print rows of statistics
    printf("%s%26f%3u%un", player_1.player, player_1.bat_avg, player_1.hr, player_1.rbi);
    printf("%s%25f%3u%un", player_2.player, player_2.bat_avg, player_2.hr, player_2.rbi);
    printf("%s%24f%3u%un", player_3.player, player_3.bat_avg, player_3.hr, player_3.rbi);

}//end of main
//BEGIN of printHeader
void printHeader() {
    printf(" Player Name   Batting Avg.  HR   RBIn");
    printf("======================================n");
}
//END of printHeader

2

Answers


  1. Use a decimal point in your format specifier, followed by a number, to specify the number of digits to be printed after the decimal point.

    Example: %.3f

    Login or Signup to reply.
  2. While you should not include pictures of code or text input/output rather than just text in your post, the solution to your problem is to use field width specifiers.

    Your already using them to specify the overall width, but you can further modify your %24f format specifier to say how many digits you’re like after the decimal point: %24.3f.

    You’ll find a good reference for these format specifiers at cppreference.com.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search