跳过数字中的数字并将未跳过的数字添加到C中

问题描述 投票:0回答:1

我正在尝试从用户输入的数字中获取所有其他数字。然后求出它们的总和。比如123456。我想得到5,3,1。然后求它们的和。这是我的职责:

int getSum(long userInput) // user input being passed as an argument.
{
   long userInput1 = userInput;
   long sumOfNum = 0 ;

 while(userInput1 != 0)
    {
      userInput1 = userInput1 / 10;
      sumOfNum += userInput1 % 10;
    }

  printf("%ld\n",sumOfNum);
} 

例如,这并不适用于所有数字; 12345,我期待 6。但输出是 10。

我哪里做错了?

[编辑-我是怎么做到的? (基于Fe2O3的回答) 我需要另一个部门。所以:

 while(userInput1 != 0)
    {
      userInput1 = userInput1 / 10;
      sumOfNum += (userInput1 % 10);
      userInput1 = userInput1 / 10; // this one
    }
   printf("%ld\n",sumOfNum);
   return sumOfNum;
}
c
1个回答
2
投票

获取每隔一个数字...

int getSum( long val ) {
    int sum = 0;
        // divide by 100 here---vvv
    for( val /= 10; val; val /= 100 )
        sum += val % 10;

    printf( "%d\n", sum ); // debugging check

    return sum;
} 
© www.soinside.com 2019 - 2024. All rights reserved.