这个程序是否正确计算5位数的总和

时间:2017-12-28 11:55:10

标签: c

程序计算五位数的总和
这个程序在编译器中显示错误,即使我认为它的事实是正确的

#include<stdio.h>

int main()
{
    int i,a,num=32765,n;
    int sum=0;

    a=num%10; 
    n=num/10;
    sum=sum+a;

    for(i=0;i>4;i++)
    {

        a=n%10;
        n=n/10; 
        sum=sum+a; 


    }

    printf("the sum of five digits is %d", sum); 

}

3 个答案:

答案 0 :(得分:2)

永远不会输入您的循环,因为i = 0且不能大于3!所以解决方案是:

int number=12345;
int total=0;
int remainder=0;

while(number>0){
remainder=number%10;
total=total+remainder;
number=number/10;
}

答案 1 :(得分:2)

您的代码中的循环永远不会输入,因为i=0然后您检查i>=3是否永远不是真的。  你可以使用这样的东西:

int digit_sum(int num){
int sum=0;
while (num !=0){
 sum += num%10;
  num = num/10;
}
  return sum;
}
int main()
{
int num = 12346;
/*
if (num <0) // add this block if negative number is posible 
    num = -num; // and its ok to change num or use some temp instead
*/
int sum = digit_sum(num);
printf("the sum of five digits is %d",sum);
 return 0;
}

或使用递归:

int digit_sum(int num){
if (num) 
   return num%10 + digit_sum(num/10);
}

答案 2 :(得分:1)

您的代码几乎是正确的,只需要正确的循环条件。添加了评论,以便您可以看到正在发生的事情:

#include <stdio.h>

int main()
{
    int i, a, num = 32765, n;
    int sum = 0;

    // extract 1st digit
    a = num % 10; // a is 5 (% returns the remainder of the division)
    n = num / 10; // n is 3276 (should be 3276.5, but int eats 0.5)
    sum = sum + a; // sum is 5 which is (0 + 5)

    // extract the remaining 4 digits
    for (i = 0; i < 4; i++) // i is 0, 1, 2, 3 
    {
        a = n % 10; // a is 6, 7, 2, 3
        n = n / 10; // n is 327, 32, 3, 0
        sum = sum + a; // sum is 11, 18, 20, 23
    }

    printf("the sum of five digits is %d", sum);
    return 0;
}

https://ideone.com/EI9tgM