When I compile the code below, the Total Votes/Percents are drawn from the row t
ID: 3741404 • Letter: W
Question
When I compile the code below, the Total Votes/Percents are drawn from the row totals and not the column totals. How can I fix this? #include <stdio.h> int main() { int votes[5][4]={ 192,48,206,37, 147,90,312,21, 186,12,121,38, 114,21,408,39, 267,13,382,29}; char cand[4]={'A','B','C','D'}; int row_totals[5]; int col_totals[4]; int total_votes; float percent[4]; int row,col; int total=0; for(row=0;row<=4;row++) { row_totals[row]=0; for(col=0;col<=3;col++) { row_totals[row] += votes[row][col]; total+=votes[row][col]; } } printf(" Candidate Candidate Candidate Candidate Total Percent "); printf(" Precinct A B C D "); for(row=0;row<=4;row++) { printf("%6d",row+1); for(col=0;col<=3;col++) { printf("%12d",votes[row][col]); } printf("%11d",row_totals[row]); percent[row]=(double)(row_totals[row]*100)/total; printf(" %.2f ",percent[row]); } int i; double first=percent[0]; double sec=percent[0]; int maxVal,second_big; for(i=0;i<4;i++) { if(first>percent[i]) { first=percent[i]; maxVal=i; } } int j; for(j=0;j<4;j++) { if(percent[j]>sec && percent[j]!=sec) { sec=percent[j]; second_big=j; } } if(first>50) { printf("%d is the winner. ",cand[maxVal]); } else if(sec<=50) { printf("%c and %c are in a runoff. ",cand[maxVal],cand[second_big]); } return 0; }
Explanation / Answer
#include <stdio.h>
int main()
{
int votes[5][4]={
192,48,206,37,
147,90,312,21,
186,12,121,38,
114,21,408,39,
267,13,382,29};
char cand[4]={'A','B','C','D'};
int row_totals[5];
int col_totals[4];
int total_votes;
float percent[4];
int row,col;
int total=0;
for(row=0;row<=4;row++)
{
row_totals[row]=0;
for(col=0;col<=3;col++)
{
row_totals[row] += votes[row][col];
total+=votes[row][col];
}
}
for(col=0;col<=3;col++)
{
col_totals[col]=0;
for(row=0;row<=4;row++)
{
col_totals[col] += votes[row][col];
}
}
printf(" Candidate Candidate Candidate Candidate Total Percent ");
printf(" Precinct A B C D ");
for(row=0;row<=4;row++)
{
printf("%6d",row+1);
for(col=0;col<=3;col++)
{
printf("%12d",votes[row][col]);
}
printf("%11d",row_totals[row]);
percent[row]=(double)(row_totals[row]*100)/total;
printf(" %.2f ",percent[row]);
}
printf("Total ");
for(col=0;col<=3;col++) {
printf("%11d",col_totals[col]);
}
printf(" ");
int i;
double first=percent[0];
double sec=percent[0];
int maxVal,second_big;
for(i=0;i<4;i++)
{
if(first>percent[i])
{
first=percent[i];
maxVal=i;
}
}
int j;
for(j=0;j<4;j++)
{
if(percent[j]>sec && percent[j]!=sec)
{
sec=percent[j];
second_big=j;
}
}
if(first>50)
{
printf("%d is the winner. ",cand[maxVal]);
}
else if(sec<=50)
{
printf("%c and %c are in a runoff. ",cand[maxVal],cand[second_big]);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.