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

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

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R