我需要在整数的偶数和奇数位添加数字。说,让数字=1234567。偶数位的总和= 2 + 4 + 6 = 12奇数位的总和= 1 + 3 + 5 + 7 = 16
我目前拥有的代码是:
int returnsum(int num) {
while(num) {
rem=num%10;
sum=sum+rem;
num=num/10);
}
while(sum) {
a=sum%10;
arr[i]=a:
sum=sum/10; i++;
}
for(i=0;a[i];i+=2) {
summ=summ+a[i];
}
return summ;
}
void main()
{
int n,m,oddSum=0,evenSum=0;
printf("Please insert the number for the program:");
scanf("%d",&n);
while (n!=0) {
oddSum += n % 10;
n /= 10;
evenSum += n % 10;
n /=10;
}
printf("Sum of digits in even places:%d\n",evenSum);
printf("Sum of digits in odd places:%d\n",oddSum);
}
最佳答案
这是您的问题的解决方案:
void main()
{
int n,m,oddSum=0,evenSum=0;
printf("Please insert the number for the program:");
scanf("%d",&n);
int flag=0;
int counter=1;
while (n!=0) {
if(counter%2==0)
{
evenSum += n % 10;
n /= 10;
}
else
{
oddSum += n % 10;
n /= 10;
}
counter++;
}
if(counter%2==0)
{
int temp=oddSum;
oddSum=evenSum;
evenSum=temp;
}
printf("Sum of digits in even places:%d\n",evenSum);
printf("Sum of digits in odd places:%d\n",oddSum);
}
关于c - C中偶数和奇数位的数字总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27836116/