用C绘制条形图

时间:2021-01-23 22:00:09

标签: arrays c graph

用户应该输入一个数组的元素(最多 20 个)。任务是使用 |、* 和 - 通过使用这些元素绘制条形图。应绘制一条减号线而不是零,并用 * 代替数组的最后一个成员。例如,如果数字是 3,则两个 |并且应该在它们上方绘制一个 * 。我的代码的问题是有时执行时间太长,在数组元素之间画一个而不是两个减号,有时不画带减号的线。

  #include <stdio.h>

   int main() {
   int n[20];
   int i,j,counter=0,input=0,min,max;
   printf("Elements of the array: \n");
   while(input!=1000){
        scanf("%d", &input);
        n[counter]=input;
        counter++;
  }
  counter--;
  min=n[0];
  max=n[0];
  for(i=1;i<counter;i++){
      if(n[i]>max) max=n[i];
      if(n[i]<min) min=n[i];
   }
 for(i=0;i<max-min+1;i++){
     for(j=0;j<2*counter;j++){
         if(j%2==0 && n[j/2]==max-i) printf("*");
         else if(i==max) printf("-");
         else if(j%2==0 && n[j/2]>0 && i<max && n[j/2]>max-i) printf("|");
         else if(j%2==0 && n[j/2]<0 && i>max && n[j/2]<max-i) printf("|");
         else printf(" ");
      }
    printf("\n");
    }
   }//  Input:4 -3 7 0 -1 1000 Expected output:
        *        
        |        
        |        
  *     |        
  |     |        
  |     |        
  |     |        
  ---------*-----
     |        *  
     |           
     *           
     My output:
      *     
      |     
      |     
  *   |     
  |   |     
  |   |     
  |   |     
  ------*---
      |     * 
      |       
      *       
 Input: 5 4 3 2 1 2 3 4 5 Expected output:
 *                       *                                          
 |  *                 *  |                                          
 |  |  *           *  |  |                                          
 |  |  |  *     *  |  |  |                                          
 |  |  |  |  *  |  |  |  |                                          
 ---------------------------
  My output:
  *               * 
  | *           * | 
  | | *       * | | 
  | | | *   * | | | 
  | | | | * | | | | //

0 个答案:

没有答案