繁体   English   中英

C 程序读取“n”个数字并找出每个数字的奇数值之和并打印出来

[英]C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them

我是编程新手,我想知道如何找到数字中的奇数。 这个程序中的条件是我们应该只使用 arrays 的概念。我为此尝试了如下代码:

#include <stdio.h>
int main()
{
int A[50],i,x,y,n,sum=0;
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++){
 x=A[i]%10;
 if(x%2!=0)
    sum=sum+x;
   A[i]=A[i]/10;
 printf("the sum of odd numbers  is %d\n",sum);}

 return 0;
 }

但在此代码仅检查循环中第一个数字的一个数字,然后下一次它将检查第二个数字的数字。 所以,我需要编写一个代码来检查数字中的所有数字,然后它转到下一个数字并检查所有数字,并且应该在循环中继续相同的过程。那么,为此我应该如何修改我的代码?

您错过了一个循环,该循环将遍历A[i]的每个数字 - 下面的内部while循环,

#include <stdio.h>

int main()
{

    int A[50], i, x, y, n, sum=0;

    printf("How many numbers will you input?\n");
    scanf("%d",&n);
    printf("the value is %d\n",n);

    for(i=0; i<n; i++) {
        scanf("%d",&A[i]);
    }

    for(i=0; i<n; i++) {
        while (A[i] > 0) {
            x = A[i]%10;
            if(x%2 != 0) {
                sum = sum + x;
            }
            A[i] = A[i]/10;
        }
        printf("the sum of odd numbers is %d\n",sum);
    }

     return 0;
}

可以在这篇文章中找到以一种很好的形式遍历每个数字的确切算法——尽管是针对不同的语言。

请注意,您还打印了中间和(有利于调试),并且我更改了一些格式 - 更多的空间、额外的大括号以及关于您提示用户输入内容的消息。

int temp;
int sum = 0;

temp = number;
do {
    lastDigit = number % 10;
    temp = temp / 10;
    sum += (lastDigit %2 != 0) ? lastDigit : 0; 
} while(temp > 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM