C-Print a histogram of the lengths of words in its input

待我称王封你为后i 2023-01-03 14:09 314阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

  1. /*
  2. * Write a program to print a histogram of the lengths of words in ts input.
  3. *
  4. * Histogram_WordLen.c - by FreeMan
  5. */
  6. #include <stdio.h>
  7. #define MAXWORDLEN 16
  8. #define IN 1
  9. #define OUT 0
  10. int main()
  11. {
  12. int c = EOF;
  13. int i = 0;
  14. int j = 0;
  15. int lens[MAXWORDLEN + 1];
  16. int state = IN;
  17. int nc = 0;
  18. for (i = 0; i < +MAXWORDLEN; ++i)
  19. {
  20. lens[i] = 0;
  21. }
  22. while ((c = getchar()) != EOF)
  23. {
  24. ++nc;
  25. if (c == ' ' || c == '\t' || c == '\n')
  26. {
  27. state = OUT;
  28. --nc;
  29. }
  30. if (state == OUT)
  31. {
  32. if (nc != 0 && nc <= MAXWORDLEN)
  33. {
  34. ++lens[nc];
  35. }
  36. state = IN;
  37. nc = 0;
  38. }
  39. }
  40. for (i = 1; i <= MAXWORDLEN; ++i)
  41. {
  42. printf("|%2d|:", i);
  43. for (j = 0; j < lens[i]; ++j)
  44. {
  45. putchar('*');
  46. }
  47. putchar('\n');
  48. }
  49. return 0;
  50. }
  51. // Here's the output of the program when given its own source as input:
  52. /*
  53. | 1|:***************************************************
  54. | 2|:****************************************
  55. | 3|:******************
  56. | 4|:********
  57. | 5|:**********
  58. | 6|:****
  59. | 7|:******
  60. | 8|:**
  61. | 9|:***
  62. |10|:**
  63. |11|:****
  64. |12|:*
  65. |13|:*
  66. |14|:*
  67. |15|:*
  68. |16|:
  69. */

发表评论

表情:
评论列表 (有 0 条评论,314人围观)

还没有评论,来说两句吧...

相关阅读