c-创建茎叶图



我正在尝试用C语言制作一个程序(用于学校用途),该程序从区间[0,99]中读取数字,并用它们制作一个茎叶图,在一行的开头加上十,然后加上所有单位。

以下是输入示例:

1 2 5 2 25 27 93 4 93 58 51

输出应为:

0 | 12245
2|57
5 | 18
9 | 333

这是我的代码:

// uloha-9-5.c -- Tyzden 9 - Uloha 5
// Adam Kotvas, 18.11.2015 10:02:12
#include <stdio.h>
int main()
{
  int n[100],i=0,j=0,l=0,desiatky[10],temp=0,k=0;
  while(scanf("%d",&n[i])>0)
  {
    if(n[i]>99 || n[i]<0){
      continue;
    }
    i++;
  }
  for(j=0;j<=10;j++)
  {
    desiatky[j]=0;
  }
  for(j=0;j<i;j++)
  {
    desiatky[(n[j]/10)%10]=1;
  }
  for(k=0;k<i;k++)
  {
  for(j=0;j<i;j++)
  {
    if(n[j]>n[j+1] && j!=i-1)
    {
      temp=n[j];
      n[j]=n[j+1];
      n[j+1]=temp;
    }
  }
  }
  for(j=0;j<10;j++)
  {
    if(desiatky[j]==1)
    {
        printf("%d | ",j);
        for(l=0;l<i;l++)
        {
          if((n[l]/10)%10==j)
          printf("%d",n[l]%10);
        }
        printf("n");
    }
  }
  return 0;
}

问题是,它适用于给定间隔内的所有数字,但当我尝试提交它时,它会显示错误的输出:(.你知道这个程序可能出了什么问题吗?

您的代码有点史诗般。更切中要害:

#include <stdio.h>
#include <stdlib.h>
int cmp(const void *av, const void *bv) { return *(int*)av - *(int*)bv; }
int main(void) {
  unsigned n[1000000], i = 0, x;
  while (scanf("%d", &x) == 1) if (x < 100) n[i++] = x;
  if (i == 0) return 0;
  qsort(n, i, sizeof n[0], cmp);
  unsigned k = 0;
  while (k < i) {
    unsigned d = n[k] / 10;
    printf("%d|", d);
    while (k < i && n[k] / 10 == d) printf("%d", n[k++] % 10);
    printf("n");
  }
  return 0;
}

最新更新