C语言求数字根的问题

ゝ一纸荒年。 2022-03-15 12:38 362阅读 0赞

数字根:
例如:234的数字根为2 + 3 + 4 = 9;238的数字根为:2 + 3 + 8 = 13, 1 + 3 = 4,则238的数字根为4。

  1. /*------------------------------------------------------------
  2. 功能:求数字根
  3. 输入每行输入一个5000位以内的数字,可输入多行,最后一行以0结束;
  4. 输出每行为对应输入行的数字根。
  5. 输入示例:
  6. 24
  7. 39
  8. 128
  9. 356
  10. 10245
  11. 0
  12. 输出示例:
  13. 6
  14. 3
  15. 2
  16. 5
  17. 3
  18. Author: Zhang Kaizhou
  19. Date:2019-3-5 18:37:15
  20. ----------------------------------------------------------------*/
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #define MAXSIZE 5000
  25. typedef struct node{
  26. char num[MAXSIZE];
  27. struct node * pnext;
  28. } Node;
  29. void list_tail_insert(Node ** pphead, Node ** pptail, char * str);
  30. void list_print(Node * phead);
  31. void calculate_number_root(Node * phead);
  32. int main(){
  33. Node * phead = NULL, * ptail = NULL;
  34. char str[MAXSIZE] = { 0 };
  35. while(scanf("%s", str), strcmp(str, "0") != 0){
  36. list_tail_insert(&phead, &ptail, str);
  37. }
  38. calculate_number_root(phead);
  39. list_print(phead);
  40. return 0;
  41. }
  42. void list_tail_insert(Node ** pphead, Node ** pptail, char * str){
  43. Node * pnew = (Node *)calloc(1, sizeof(Node));
  44. strcpy(pnew->num, str);
  45. if(* pphead == NULL){
  46. * pphead = pnew;
  47. * pptail = pnew;
  48. }else{
  49. (* pptail)->pnext = pnew;
  50. * pptail = pnew;
  51. }
  52. return;
  53. }
  54. void list_print(Node * phead){
  55. while(phead != NULL){
  56. printf("%s\n", phead->num);
  57. phead = phead->pnext;
  58. }
  59. return;
  60. }
  61. void calculate_number_root(Node * phead){
  62. int i, sum = 0;
  63. char str[10] = { 0 };
  64. while(phead != NULL){
  65. for(i = 0; i < strlen(phead->num); i++){
  66. sum += phead->num[i] - '0';
  67. }
  68. sprintf(str, "%d", sum); // 将一个整数转换成字符串
  69. strcpy(phead->num, str);
  70. if(sum >= 10){
  71. calculate_number_root(phead);
  72. }
  73. sum = 0;
  74. phead = phead->pnext;
  75. }
  76. return;
  77. }

发表评论

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

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

相关阅读

    相关 数字

    数字根 一个正整数的数字根式通过计算该整数的各位和产生的。 如果一个整数的各位和为一位整数,那么这个数字就是该整数的数字根。 如果该整

    相关 C语言 数字乘积

    任务描述 从终端输入正整数,求该整数的数字乘积根。 功能要求 ①本程序要求可以连续求得多个整数的数字乘积根,直到用户输入数字0时,退出程序。 ②在主函数中输入正

    相关 二分法问题

    一类问题:定义在\[L,R\]上的单调函数f(x),求方程f(x)=0的根。 1).计算√2的近似值 注意:由于根号√2是无理数,因此只能获得它的近似值,不妨精