简体   繁体   中英

Problems with my 2D array when trying to create vertical graph/histogram

I need to read in integer values from user, and then organize them in the order it was inputted in a vertical graph with "#". Everything works except 3 things:

  1. The last column gets printed twice
  2. There are some weird #s floating in the top row for some reason

3.Sometimes for example, 7 and 8 both output same number of #s

I appreciate those that take their time and help me out, I am kind of new to Coding. Thank you in advance.

Desired Example I/O:

15
16
15
12
12
12
8
6
3
2
19
21
17
15
12
11
10
9
8
7
7
Output:
            #
            #
           ##
           ##
           ###
  #        ###
 ###       ####
 ###       ####
 ###       ####
 ######    #####
 ######    ######
 ######    #######
 ######    ########
 #######   #########
 #######   ###########
 ########  ###########
#########  ###########
#########  ###########
########## ###########
######################
######################

Example Input/Output of my code:

1
2
3
4
5
6
7
8
8
9
###########
       ####
      #####
     ######
    #######
   ########
  #########
 ##########
###########

My code:

#include <stdio.h>

int main () {
int input, num, max=0, nums=0;
int numbers[80]; 


  while (input != EOF) {
    input = scanf("%d", &num);
    if (num > max) {
      max=num;}
  numbers[nums] = num;
  nums++;
  }


int histogram[nums][max];
for (int i = 0; i < nums; i++){
  if (numbers[i] != 0){
   for (int j=0; j <= numbers[i]; j++) {
    histogram[i][j] = 1;
    }
  }
}

for (int j = max; j > 0 ; j--){
  for (int i = 0; i <  nums; i++) {
    if (histogram[i][j]==1) {
      printf("#");
    } else {
      printf(" ");
    }
  }
  printf("\n");
}




return 0;
}

First, you check for whether or not input is EOF before assigning to input, when you should do it after. A quick/dirty way of doing that would be:

while ((input = scanf("%d", &num)) != EOF) {
    ...
}

Second, your j loops don't match. I'd recommend making them both go from width-1 to 0, like so:

for (int j=0; j < numbers[i]; j++) {
for (int j = max-1; j >= 0 ; j--){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM