(C)代码无法处理所有需要的条件

时间:2017-11-25 13:00:40

标签: c

#include <stdio.h>
#include <stdlib.h>

#define TEN 10 
int main ()
{
 int number = 0;
 int digit = 0;
 int last_digit = 0;
 int digit_sum = 0;
 int i = 0;
while (i == 0)
{
 printf("Please Enter A Positive Number! \n"); //explaining
 scanf("%d",&number);
 if (number > 0)
{
    i++;
}

}

    while (number > 0)
    {
    digit = number % TEN; //breaking number into digits
    number /= TEN;

    if (last_digit != digit) //comparing digits
    {
       last_digit = digit;
       digit_sum += digit;
    }


    }


    printf("The Sum Of The Digits Is : %d",digit_sum);
    return 0;

}

代码会将数字分成数字并检查是否有加号数字,如果存在,只会计算其中一个数字:3211 3 + 2 + 1,但我的问题是,代码不能使用像31211这样的数字我感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

将数字转换为字符串使用itoa()。对它进行排序,然后遍历它,寻找唯一的数字并进行计算