Can anyone help me fix problem?

Asked

Viewed 80 times

-2

Action

Receive two integers from the user, the first being the digit you want to know how many times it appears and the second being the contact number.

In and out

Entree:

Integer value A (between 1 and 9).
Integer value B.

Exit:

Number of times digit A appears in B

#include <stdio.h>

    int main(void)
   {

       int contaDigitos = 0, valor;
       scanf("%d", &valor);
       if (valor == 0) contaDigitos = 1;
       else
            while (valor != 0)
           {
             contaDigitos = contaDigitos + 1;
               valor = valor / 10;
           }
      printf("%d\n", contaDigitos);
      return 0;
 }
  • 1

    Therefore, although you have a well trained eye here, try to explain better what problem you are having, so that the staff can help you without having to figure out/guess, editing your question (probably help will come faster like this) - take advantage and do the tour and read here how to ask

  • 1

    something like: "I am making a program that does X - when compiling, the error is Y - or, when executing, instead of the expected result, it shows Z" - ah, and welcome to the stackoverflow! =)

1 answer

0

First you should read two values A and B, but you’re just reading the B.

Within the while, you should check the digit of the valor % 10 is the value of A and only then increment the contaDigitos.

Your if (valor == 0) contaDigitos = 1; also makes no sense. Just use the while who is in the else.

You can also simplify valor = valor / 10; for valor /= 10; and contaDigitos = contaDigitos + 1; for contaDigitos++;. I also recommend renaming the variable valor for b in accordance with the plan for the financial year.

Your code goes like this:

#include <stdio.h>

int main() {
    int contaDigitos = 0, a, b;
    scanf("%d %d", &a, &b);
    while (b != 0) {
        if (b % 10 == a) contaDigitos++;
        b /= 10;
    }
    printf("%d\n", contaDigitos);
    return 0;
 }

With the entrance 5 57565503 it produces the output 4. See here working on ideone..

Ah, that won’t work for B values greater than 2147483647 due to an overflow, but I think for the purposes of your exercise, that’s okay.

Browser other questions tagged

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