Infinite loop in height growth analysis

Asked

Viewed 54 times

0

Gustavo is 1.40 meters and grows G centimeters per year, while Juliano is 1.10 and grows J centimeters per year.

My show is giving a loop infinite when I run.

#include<stdio.h>
int main()
{

float g,j,gus=1.40,jul=1.10;
int cont=0;

scanf("%lf %lf",&g, &j);

while(jul<=gus)
{
    jul=jul+j;
    printf("%lf\n",jul);

    gus=gus+g;
    printf("%lf\n",gus);

    cont++;

}
printf("%d",cont);


}
  • 2

    Hello Flávio, probably the jul is not reaching the value of Gus;

  • 1

    And what should I do? It depends on the input, if j is less than or equal to g this is the correct behavior. It should have a test stop point to be something that has some logic. Maybe the exercise was ill-defined, but we don’t know what he looks like.

  • sure would be if I put as input 8 and 17, the cont should come out 4, being that jul surpassed Gus, but stays in the loop, which can be?

  • There seems to be a problem of magnitude of measures there, need to decide whether to work with meters or will convert between them. What is right?

  • Change to while(jul<=gus && cont < 20) and say what appears on the way out.

  • i managed to tidy up now, instead of by %lf, I put %f and divide g and j by 100 before adding, now ta hitting. vlw guys

  • That? https://ideone.com/GsqXRf

  • Yeah, now it’s out of the loop and it’s hitting the result, vlws

Show 3 more comments

1 answer

2


Stated how float use the formatting of scanf() as %f.

You have to test to see if Gustavo grows smaller or equal to Juliano, otherwise it will always be infinite anyway, is mathematician.

And it needs to normalize. It’s working originally with meters, and it asks to type centimeters, so it needs to divide by 100.

The most certain would be to make other validations, but for exercise this is good.

#include<stdio.h>

int main() {
    float g, j, gus = 1.40, jul = 1.10;
    int cont = 0;
    scanf("%f %f", &g, &j);
    if (g <= j) {
        printf("Nunca alcancará");
        return 0;
    }
    g /= 100;
    j /= 100;
    while (jul <= gus) {
        jul += j;
        printf("%lf\n", jul);
        gus += g;
        printf("%lf\n", gus);
        cont++;
    }
    printf("%d", cont);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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