Program in C to generate terms from a P.G

Asked

Viewed 2,555 times

3

I am a beginner to the C language, and found a problem in the code below.

The question is as follows: The program runs perfectly, but when inserting values such as (1-5-3), the program, which should return (1-5-25), returns (1-5-24).

I’ve revised my code several times, and the remake, however, the error thrives.

P.S.: After several tests, I realized that the error happens when 'rate' has a value ending 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);
    }
}
  • I apologize for the simple question, as I said, I am a beginner, currently studying by the site cprogressivo.net, and I intend to delve into the language C.

  • The way out worked for me.

  • The output is also correct for me. I see no problems in the code.

  • Like I said, there doesn’t seem to be anything wrong here. The only thing I would recommend are a few frills: you can declare the thermo_pg variable inside the loop instead of at the top of the function and you could have done it from scratch: for(count = 0; count < n; count++). In addition to saving the "-1" in the account, iterating from scratch is the "default" in C (this will be clear when you start seeing vectors)

  • It’s easy to test (and realize that, as colleagues have said, it doesn’t seem wrong) here: https://ideone.com/wAMwGI

  • that OS and compiler are using?

  • Thank you so much for the answers! I tested the code on another computer, and it also worked. Maybe, the error is in my old laptop itself, will understand.

  • Hugomg, grateful for the tips, I will follow the recommendations. pmg, I am currently using Windows 7, and the compiler Code::Blocks

Show 3 more comments

2 answers

1

Maybe your pow() be 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 work only with integers, without inserting floating comma into the problem (you can stop using <math.h>).

1

Because the Pow function works with floating point numbers, a rounding or truncation problem may actually occur.

It’s very simple to make 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;
}

Browser other questions tagged

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