我想做一个直方图垂直显示我的"选举"。我的代码工作只是它似乎错误地显示了10,11,12,13值的投票,因为我认为有2个数字。。。感谢您抽出时间;(
int main() {
char character ;
int TAB[12] = {0} ;
int vote = 0;
int I;
printf("Please enter a character:n"); //character for the display
scanf(" %c", &character); // character we want to display in the histogram
printf("Please enter votesn");
while(1) {
scanf("%d", &vote);
if (vote == -1) {
break;
}
TAB[vote-1]++; //save the vote into the array
}
printf("Histogram :n");
/* Search for the maximum value */
int MAX=0;
for (I=0; I<12; I++)
{
if(TAB[I]>TAB[MAX]) MAX=I;
}
int maximum = TAB[MAX]; // maximum value
while (maximum > 0) {
for (I = 0; I < 12; I++) {
if (TAB[I] == maximum) {
printf("%c ",character);
TAB[I] = (TAB[I] - 1) ;
}
else {
printf(" ");
}
}
maximum= maximum - 1;
printf("n");
}
for (I = 0; I < 13; I++) {
printf("%d ",I+1); // display the number of each candidat
}
printf("n"); // go to the line
return 0;
}
- 你不应该使用幻数
12
,像#define VOTE_MAX 13
一样使用 - 对于
vote
的范围,请使用if (vote <= 0 || vote > VOTE_MAX)
- 格式输出,
like printf("%2c ", character);
- 线路
for (I = 0; I < 13; I++) {
应为for (I = 0; I < 12; I++) {
以下代码可以工作:
#include <stdio.h>
#define VOTE_MAX 13
int main() {
char character;
int TAB[VOTE_MAX] = {0};
int vote = 0;
printf("Please enter a character:n"); // character for the display
scanf(" %c", &character); // character we want to display in the histogram
printf("Please enter votesn");
while (1) {
scanf("%d", &vote);
if (vote <= 0 || vote > VOTE_MAX) {
break;
}
TAB[vote - 1]++; // save the vote into the array
}
printf("Histogram :n");
/* Search for the maximum value */
int MAX = 0;
for (int i = 0; i < VOTE_MAX; ++i) {
if (TAB[i] > TAB[MAX]) MAX = i;
}
int maximum = TAB[MAX]; // maximum value
while (maximum > 0) {
for (int i = 0; i < VOTE_MAX; ++i) {
if (TAB[i] == maximum) {
printf("%2c ", character);
--TAB[i];
} else {
printf("%2c ", ' ');
}
}
--maximum;
printf("n");
}
for (int i = 0; i < VOTE_MAX; ++i) {
printf("%2d ", i + 1); // display the number of each candidat
}
printf("n"); // go to the line
return 0;
}
您需要为I
为10或更高的情况添加额外的空间。
类似:
for (I = 0; I < 12; I++) {
if (TAB[I] == maximum) {
printf("%c ",character);
TAB[I] = (TAB[I] - 1) ;
}
else {
printf(" ");
}
if (I >= 9) printf(" "); // Add extra space for 10, 11 and 12
}
BTW:你的输入法应该改进一下。目前,用户可以输入将在数组之外进行写入的值。至少做一些类似的事情:
while(1) {
if (scanf("%d", &vote) != 1) break; // Catch illegal input
if (vote <= 0 || vote >= 13) { // Only allow vote to be 1, 2, …, 10, 11, 12
break;
}
TAB[vote-1]++; //save the vote into the array
}