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.
– José Dantas
The way out worked for me.
– pmargreff
The output is also correct for me. I see no problems in the code.
– Augusto
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)– hugomg
It’s easy to test (and realize that, as colleagues have said, it doesn’t seem wrong) here: https://ideone.com/wAMwGI
– Luiz Vieira
that OS and compiler are using?
– pmg
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.
– José Dantas
Hugomg, grateful for the tips, I will follow the recommendations. pmg, I am currently using Windows 7, and the compiler Code::Blocks
– José Dantas