Can anyone help me to fix the problem?

-2
  

Action

     

Get 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.

     

Input and Output

     

Entry:

     

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

     

Output:

     

Number of times the 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;
 }
    
asked by anonymous 15.09.2018 / 00:33

1 answer

0

First you should read two A and B values, but you are only reading B.

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

Your if (valor == 0) contaDigitos = 1; does not make sense either. Just use the while that is in else .

You can also simplify valor = valor / 10; to valor /= 10; and contaDigitos = contaDigitos + 1; to contaDigitos++; . I also recommend renaming the variable valor to b to conform to the exercise statement.

Your code looks 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 input 5 57565503 it output 4 . See here working on ideone. .

Ah, this will not work for B values greater than 2147483647 due to an overflow, but I think for the purposes of your exercise, this is ok.

    
15.09.2018 / 01:35