问题从阵列的最底部开始。我打印百分比[x]值以确保它们在那里,然后在排序后,其中三个用零填充。我一直在寻找一段时间但我找不到任何东西。
#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]; //This is left for you to do
//see code below to see how
//row_totals were calculated.
int total_votes;
//use a for loop to calculate
//using either row_totals or col_totals
float percent[4]; //use a for loop to calculate based on
int swap; //total_votes and col_totals
//be sure to print the totals for the candidates
//at the end, you will need to sort the percent array
//bringing along the values from the cand array. That is
//if a swap is made in the percent array, do the same
//swap in the cand array.
//then if percent[3] is greater than 50, declare cand[3] the winner
//if percent[3] is not greater than 50, declare a run-off
//between cand[2] and cand[3]
int row,col;
for(row=0;row<=4;row++) // used to find the row total
{
row_totals[row]=0;
for(col=0;col<=3;col++)
{
row_totals[row] += votes[row][col];
}
}
for(col=0; col <=3; col++)
{
col_totals[col]=0;
for(row =0; row <= 4; row++) // used to find the column total
{
col_totals[col] += votes[row][col];
}
}
for(row =0; row<=4; row++)
{
total_votes += row_totals[row]; //finds the total amount of the votes
}
printf(" Candidate Candidate Candidate Candidate Total\n");
printf(" Precinct: A B C D Votes\n");
for(row=0;row<=4;row++)
{
printf("%6d",row+1);
for(col=0;col<=3;col++)
{
printf("%12d",votes[row][col]);
}
printf("%11d\n",row_totals[row]);
}
printf("Total\nVotes:");
for(col=0; col<=3; col++)
{
printf("%12d", col_totals[col]);
}
printf(" %d", total_votes);
printf("\nPrecentage:");
for(col=0; col <= 3; col++)
{
percent[col] = (col_totals[col] / (double)total_votes); //calculates percentages
printf("%11f", percent[col]);
}
int x,y;
for(x=0; x<=3; x++)
{
printf("\n%f", percent[x]);
}
for(x=0; x<3; x++)
{
for(y=0;y<(3-x); y++)
{
if(percent[y] > percent[y+1])
{
swap = percent[y];
percent[y] = percent[y+1];
percent[y+1]= swap;
}
}
}
for(col=0; col<4; col++)
{
printf("\n%f", percent[col]);
}
return 0;
答案 0 :(得分:1)
用于交换的临时变量是一个整数,但是您交换的值在0到1之间浮动,在转换为int
时将变为零。
错误很难发现,因为临时变量声明在long main
函数的顶部,远离实际的交换代码。您可以将临时变量设置为交换范围的局部变量:
for (x = 0; x < 3; x++) {
for (y = 0; y < (3 - x); y++) {
if (percent[y] > percent[y + 1]) {
float swap = percent[y];
percent[y] = percent[y + 1];
percent[y + 1] = swap;
}
}
}
其他问题:
您的total_votes
未初始化为零。
请考虑将您的循环编写为
for (row = 0; row < nrows; row++) ...
而不是
for (row = 0; row <= nrows - 1; row++) ...
这是一种常见的C语言。您的循环使用硬编码值,但稍后您可能希望具有上述两个示例中的变量限制,其中“少于项目数”变体更具可读性。
打印时,新行应位于打印格式的末尾,而不是开头。这是自然的印刷方式。它还具有在向控制台打印换行符时刷新输出缓冲区的好处。
这是次要的,但选择一个浮点类型。您使用float
,但使用double
计算您的百分比。我推荐double
,这是现代机器上的标准浮点类型。