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

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;
    改一下就好

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用