How to get all the digits of a variable in C?

Asked

Viewed 1,005 times

1

I have to do a function that tests divisibility by 3, return true if divisible by 3. Otherwise return false. Following the rule : A number is divisible by 3 when the sum of its digits is divisible by three.

I have the following variables: :

int dividendo;
int divisor;

And I have the following function :

int divisibilidade3(int num);

I need to separate the digits from the variable dividendo, for example, when the user enters with the splitter 3 I’ll call the function divisibilidade3and I will check if the final digit ends with 3, 6 or 9.

For example, if the user enters the number 25848, I need to break this number into pieces, being then : 2+5+8+4+8 = 27 e 2+7 = 9, how is it 9 the final result, then it is divisible by 3.

The function should repeat the digit summation process of the results obtained until the sum is a number with one digit. If this digit is 3, 6 or 9, so the original number is divisible by 3.

I will have to follow all these rules using divisibility criteria. If anyone can help me, I am grateful.

  • If I understand correctly, you want to create a function that shows that a given number is divisible by 3, you cannot use the mod?

  • 1

    I can use mod to some extent, but I can’t check for example whether %b == 0 is divisible or not. I have to follow the divisibility criteria.

  • 1

    The mod indicates the rest of the division, if it is 0 means that the number is divisible by the value.

2 answers

2


#include <stdio.h>

int Divisibilidade( int num )
{
    int res = 0;

    while( num > 0 )
    {
        res += num % 10;
        num /= 10;
    }

    if(res > 9)
        return Divisibilidade( res );
    else
        return (res%3);
}


int main()
{
    int n;

    while(1)
    {
        scanf("%d", &n);

        printf("O numero %se divisivel.\n", !Divisibilidade(n) ? "" : "nao ");
    }

    return (0);
}

0

I suspect your teacher will simply imagine that you will turn the number into a string using snprintf(), and then iterate on the sequence:

#include <stdio.h>
#include <stdlib.h>

int
divisivel_por_3(int num) {
    char algs[12];
    char * ptr;

    // Se o número for negativo, troca o sinal (não afeta a divisibilidade)
    if (num < 0) num = -num;
    do {
        // Transforma o número em string
        if (snprintf(algs, sizeof(algs), "%d", num) < 1) {
            fprintf(stderr, "Falha na determinação dos algarismos de %d\n", num);
            exit(EXIT_FAILURE);
        }
        // itera sobre os algarismos de num, substituindo-o
        // pela soma de seus próprios algarismos
        for (num = 0, ptr = algs; *ptr; ptr ++) {
            num += (*ptr) - '0'; // transforma o dígito ASCII '0'-'9' no inteiro 0-9
    } while (num >= 10);

    return (num == 3) || (num == 6) || (num == 9);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.