How do I solve an alternative power problem?

0

I need help solving a power problem in an alternate way.

The purpose is to show the result of the potentiation and the number of characters (or numbers) that appear in the result. The code I'll put next I got put to work through some conversions from character to integer and vice versa.

base = input('Base: ')
expoente = input('Expoente: ')
potencia = int(base) ** int(expoente)
print('Potência: %d' %potencia)
digito = len(str(potencia))
print('Digitos: %d' %digito)

However, when I made a call not specifically to the math library, I did not succeed in solving the problem. The result of the potencia variable is correct, but the result of the digito variable appears erroneously.

The code that did not work is similar to the previous one, it only has the changes changes below compared to the above.

# potencia = int(base) ** int(expoente) (Colocado como comentário para visualização)
import math
potencia = math.pow(int(base),int(expoente))

I do not know if the result of the variable potência is an integer after the call of the mathematical library, or a variable of character type, even so I am trying to carry out the conversion of the supposed whole number to character through the use of the function len() .

How could you solve the problem according to the second code?

    
asked by anonymous 10.04.2017 / 18:16

1 answer

2

The output is completely correct.

See the example

import math
res = math.pow(2, 8) # Saída: 256.0
len(str(res)) # Saída: 5

This is because converting the variable res (which is of type float ) to string also takes into account the floating point and the decimal place.

If you want to ignore the decimal places if the number is integer, you can do the verification using the is_integer() function.

Example:

import math

def teste(base, exp):
    res = math.pow(base, exp)
    digitos = 0    

    if(res.is_integer()):
        digitos = len(str(int(res)))
    else:
        digitos = len(str(res))

    print('resultado: %s \t digitos: %s' % (res, digitos))

teste(2, 8)      #resultado: 256.0         digitos: 3
teste(1.5, 8)    #resultado: 25.62890625   digitos: 11
teste(3.0, 8)    #resultado: 6561.0        digitos: 4
    
10.04.2017 / 19:09