垂直直方图打印问题

时间:2014-10-13 16:38:14

标签: c histogram

for (a = 0; a < 9; a++)
{
    if (hm <= arr[a]) //hm is Maximum number in array for height of a column.
        hm = arr[a];
}
for (i = hm; i >= 0; i--)
{
    for(t = 0; t < width; t++) //Width is where i got in trouble.
    { 
        printf("|");
        for (a = 0; a < 9; ++a)
        { 
            if (arr[a] > i)
            {       
                printf("*|");
            }
            else
            {
                printf(" |");
            }
        }
        printf("\n");
    }
}

所以我现在有了这个代码。我从用户那里得到9个数字输入并将其转换为垂直直方图。例如,当用户输入1-2-2-4 -....并输入宽度为3时;输出是:

  | |*|         //Prints "width" as height.
  | |*|
  | |*|
  |*|*|
  |*|*|
  |*|*|.....

我希望它像:

  |   |   |
  |   |   |
  |   |***|
  |***|***|.....
    1   2

有没有办法用我的代码实现这个输出?对不起,如果我不清楚,我不擅长英语。我也是C编程的新手,仍然试图理解它的行为。谢谢!

1 个答案:

答案 0 :(得分:1)

此代码按照您说的那样工作

for (int a = 0; a < 9; a++) {
    if (hm <= arr[a]) //hm is Maximum number in array for height of a column.
        hm = arr[a];
}
for (int i = hm; i >= 0; i--) {
    printf("|");
    //for(int t = 0; t < width; t++){ //Width is where i got in trouble.
        //printf("|");
        for (int a = 0; a < 9; ++a) {
            if (arr[a] > i) {
                for(int t = 0; t < width; t++){ //Here where you should have added the for loop
                    printf("*");
                }
                //printf("*|");
                printf("|");
            }
            else{
                for(int t = 0; t < width; t++){ //Here where you should have added the for loop
                    printf(" ");
                }
                printf("|");
                //printf(" |");
            }
        }
        printf("\n");
    //}
}
return 0;