I'm new to C and I've been working on some code for a project for school. This was the finished result and now that I'm done it, I came back and tried making it better. So I was wondering, how would I make this printAvgCalPerGroup
simplified?
#include "diary.h"
void printTotalCal(Food * list)
{
int total = 0;
Food * temp = list;
while (!isEmpty(temp))
{
total += (int)temp->calories;
temp = temp->next; // change to the next list item
}
printf("%d\n", total);
return;
}
void printAvgCalPerGroup(Food * list)
{
double vegCount = 0.0;
double meatCount = 0.0;
double dairyCount = 0.0;
double grainsCount = 0.0;
double fatCount = 0.0;
double vAmnt = 0.0;
double mAmnt = 0.0;
double dAmnt = 0.0;
double gAmnt = 0.0;
double fAmnt = 0.0;
Food * temp = list;
while (temp!= NULL)
{
if (temp->foodGroup[0] == 'v')
{
vAmnt+=1.0;
vegCount+=temp->calories;
}
else if (temp->foodGroup[0] == 'm')
{
mAmnt+=1;
meatCount+=temp->calories;
}
else if (temp->foodGroup[0] == 'd')
{
dAmnt+=1;
dairyCount +=temp->calories;
}
else if (temp->foodGroup[0] == 'g')
{
gAmnt+=1;
grainsCount+=temp->calories;
}
else if (temp->foodGroup[0] == 'f')
{
fAmnt+=1;
fatCount+=temp->calories;
}
temp = temp->next;
}
printf("%.2f\n", calcAvg(vegCount,vAmnt));
printf("%.2f\n", calcAvg(meatCount,mAmnt));
printf("%.2f\n", calcAvg(dairyCount,dAmnt));
printf("%.2f\n", calcAvg(grainsCount,gAmnt));
printf("%.2f\n", calcAvg(fatCount,fAmnt));
}
double calcAvg(double x, double y)
{
double ans = x/y;
if (ans != ans) return 0.0;
return ans;
}
void run(char * argv)
{
Food * f = getDiary(argv);
printTotalCal(f);
printAvgCalPerGroup(f);
printList(f);
destroyList(f);
}