C program to generate terms of a P.G

3

I'm a beginner to the C language, and I encountered a problem in the code below.

The problem is this: The program runs perfectly, however, when entering values like (1-5-3), the program, which should return (1-5-25), returns (1-5-24) .

I've reviewed my code several times, and have re-read it, but the error thrives.

Q: After several tests, I noticed that the error happens when 'rate' has a value that ends in 5 , for example: 5, 15, 155.

#include <stdio.h>
#include <math.h>

int main()

{
    int init, rate, n_terms, termo_pg,
        count;

    printf("Elemento inicial da P.G.: \n");
    scanf("%d", &init);

    printf("Razao da P.G.: \n");
    scanf("%d", &rate);

    printf("Numero de termos da P.G.: \n");
    scanf("%d", &n_terms);

    for (count = 1; count <= n_terms; count++)
    {
        termo_pg = init*pow(rate, count-1);
        printf("Elemento %d da P.G.: %d \n", count, termo_pg);
    }
}
    
asked by anonymous 27.04.2015 / 02:42

2 answers

1

Maybe your pow() is weird and pow(5, 3) == 124.9999999999213453562 .

Suggestion:

termo_pg = init * pow(rate, count-1) + 0.000001; // arredonda para cima

or write a function similar to pow that works only with integers, without entering a floating point in the problem (you can stop using <math.h> ).

    
27.04.2015 / 08:26
1

Since the pow function works with floating-point numbers, a rounding or truncation problem may actually be occurring.

It's quite simple to do an exponentiation function with integers:

long potencia(long base, long expoente)
{
    long i;
    long r = 1;

    for( i = 0 ; i < expoente ; i++ )
        r = r * base;

    return r;
}
    
04.05.2015 / 06:32