A baseball player\'s batting average is calculated as the number of hits divided
ID: 3544757 • Letter: A
Question
A baseball player's batting average is calculated as the number of hits divided by the official number of at-bats. In calculating official at-bats, walks, sacrifices, and occasions when hit by the pitch are not counted. Write a program that takes an input file containing player numbers and batting records. Trips to the plate are coded in the batting record as follows: H--hit, O--out, W--walk, S--sacrifice, P--hit by pitch. The program should calculate each player's batting average.
(You will use argv[1] as name of file in fopen() function call.)
Example:
12 HOOOWSHHOOHPWWHO
4 OSOHHHWWOHOHOOO
7 WPOHOOHWOHHOWOO
Player 12's record: HOOOWSHHOOHPWWHO
Player 12's batting average: 0.455
Player 4's record: OSOHHHWWOHOHOOO
Player 4's batting average: 0.417
Player 7's record: WPOHOOHWOHHOWOO
Player 7's batting average: 0.364
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char **argv) {
int player,totalcount=0,hitscount=0,i;
double avg;
char hits[1000];
FILE *fp;
fp=fopen(argv[1],"r+");
while(fscanf(fp,"%d%s",&player,hits)!=-1)
{
avg=0;
totalcount=0;
hitscount=0;
for(i=0;i<strlen(hits);i++)
{
if(hits[i]=='H')
{
hitscount++;
totalcount++;
}
else if(hits[i]=='O')
totalcount++;
}
avg=hitscount/totalcount;
printf("Player %d's record: %s ",player,hits);
printf("Player %d's batting average: %lf",avg);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.