分割数字然后求和的函数

时间:2019-06-18 11:36:37

标签: c function split sum digits

我正在尝试解决一个需要我打电话的问题。使用%和/取最右边的数字并加总分开的数字。然后告诉数字是否可以被9整除。

我创建了一个将最右边的数字分隔开的函数,然后尝试使用该数字并通过while循环运行它。存在的问题是,当我运行while循环时。它将创建一个无限循环,否则将不会打印输出。

#include <stdio.h>

int loopnum(int n);

int main(void)
{
    int num;
    int sum = 0;
    int d = loopnum(num);

    printf("Enter a number:\n");
    scanf("%d", &num);

    while (loopnum(num) > 0) {
        printf("d = %d", d);
        printf(",sum = %d\n", sum);
    }

    if (num % 9 == 0) {
        printf("n = %d is divisible by 9\n", num);
    }
    else {
        printf("n = %d is not divisible by 9\n", num);
    }
    return 0;
}

int loopnum(int n)
{
    n = n % 10;
    n = n / 10;
    return n;
}
Enter a number:
9
n = 9 is divisible by 9

该代码的结果假定为输出d =“数字”,sum = “ digit + sum”和n =“ digit”可被9整除。例如,如果我 输入9。输出将为d = 9,总和= 9。

2 个答案:

答案 0 :(得分:0)

loopnum代码错误。它将始终返回零,因此while将不会循环。

int loopnum(int n)
{
    n = n % 10;  // After this n is a number between 0 and 9
    n = n / 10;  // Consequently, when you divide by 10 you'll end up with zero
    return n;
}

您的设计需要两件事:

1)返回余数

2)更改n

为此,您需要将指针传递到n

类似的东西:

int loopnum(int *n)
{
    int res = *n % 10; 
    *n = *n / 10;
    return res;
}

int main(void)
{
  int x = 123;
  int sum = 0;
  while(x) sum += loopnum(&x);
  printf("%d\n", sum);
  return 0;
}

答案 1 :(得分:0)

该功能没有意义。

int loopnum(int n)
{
    n = n % 10;
    n = n / 10;
    return n;
}

例如对于n等于27,您将得到

n = n % 10;

现在n等于7,然后

n = n / 10;

现在n等于0

因此对于数字27,该函数返回0

而且在循环内

while (loopnum(num) > 0) {
    printf("d = %d", d);
    printf(",sum = %d\n", sum);
}

numdsum均未更改。

定义这样的功能没有什么意义,除了它本身可以输出中间的和和数字外。

如果没有该功能,程序的外观将如下所示。

#include <stdio.h>

int main(void) 
{
    while ( 1 )
    {
        const unsigned int Base    = 10;
        const unsigned int DIVISOR = 9;

        printf( "Enter a non-negative number (0 - exit): " );

        unsigned int n;

        if ( scanf( "%u", &n ) != 1 || n == 0 ) break;

        unsigned int sum = 0;

        unsigned int tmp = n; 
        do
        {
            unsigned int digit = tmp % Base;
            sum += digit;

            printf( "d = %u, sum = %u\n", digit, sum );
        } while ( tmp /= Base );

        printf( "\nn = %u is %sdivisble by %u.\n\n", 
                 n, 
                 sum % DIVISOR == 0 ? "" : "not ", DIVISOR );

    }

    return 0;
}

其输出可能看起来像

Enter a non-negative number (0 - exit): 9
d = 9, sum = 9

n = 9 is divisble by 9.

Enter a non-negative number (0 - exit): 123456
d = 6, sum = 6
d = 5, sum = 11
d = 4, sum = 15
d = 3, sum = 18
d = 2, sum = 20
d = 1, sum = 21

n = 123456 is not divisble by 9.

Enter a non-negative number (0 - exit): 0