首页 > 文章列表 > C程序计算奇数位数和偶数位数之差

C程序计算奇数位数和偶数位数之差

C程序 奇偶差 位数计算
391 2023-08-21

给定一个数字,找出奇数位数和偶数位数之间的差异。这意味着我们将计算所有偶数位数和所有奇数位数,并将它们的总和相减。

示例

Input:12345
Output:3

Explanation

the odd digits is 2+4=6
the even digits is 1+3+5=9
odd-even=9-6=3

Taking every digit out of number and checking whether the digit is even or odd if even then add it to even sum if not then to odd sum and then take difference of them.

Example

#include <iostream>
using namespace std;
int main() {
   int n, r=0;
   int diff =0;
   int even=0;
   int odd=0;
   n=12345;
   while(n != 0){
      r = n%10;
      if(r % 2 == 0) {
         even+=r;
      } else {
         odd+=r;
      }
      n/=10;
   }
   diff=odd-even;
   printf("%d",diff);
   return 0;
}