weixin_43206711
2018-09-23 02:23
采纳率: 100%
浏览 1.2k
已采纳

Digital Roots 题目大意将输入的正整数的各个数相加

题目如下
The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.
For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

输入

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

输出

For each integer in the input, output its digital root on a separate line of the output.

样例输入

24
39
0

样例输出

6
3

我的思路是
1.将sum各位数字加起来,赋值sum
2.判断sum是否是个位数,如果不是,转1
3是个位数,输出结果,运算结束
sum%9的结果和整个数模9的结果相同,用来运算各个书之和。以下是我的代码。思路看起来没问题,但是运行结果和想象的不一样。

 #include <stdio.h>
int main()
{
    char ch;
    while(1){  //计算各位数字的和
    int sum;
    while(scanf("%c",&ch) && ch!='\n'){
        sum+=ch-'0';
        }
    if (sum==0) break;
    //模9运算求根
    if(sum%9==0) sum=9;
    else sum=sum%9;
    printf("%d\n",sum);
    }
    return 0;
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 扫眉 2018-09-23 02:27
    已采纳

    思路是没问题,但是你没有初始化sum,结果就会错。
    简单地说就是 int sum=0;
    改一下就好

    点赞 打赏 评论

相关推荐 更多相似问题