TOPIC

3 ultimas iterações errado, alguém enxerga o erro?

Renan Alcoléa asked 1 year ago

#include<stdio.h>
#include <stdlib.h>

int main() {

   int aux;
   float i=0.0,j=1.0;

   for(aux=1;aux<=33;aux++){

       if(i == 0 || i == 1 || i == 2 || i == 3 || j == 0 || j ==1 || j == 2 || j == 3 || j == 4 || j == 5){

               printf("I=%.0f J=%.0f\n",i,j);
               j++;
               if(aux % 3 == 0){
                  i+=0.2;     
               }
               if(aux % 3 == 0){
                  j-=3; 
                  j+=0.2; 
               }
       }

       else{ 
               printf("I=%.1f J=%.1f\n",i,j);
               j++;
               if(aux % 3 == 0){
                  i+=0.2;     
               }
               if(aux % 3 == 0){
                  j-=3; 
                  j+=0.2; 
               }
       }

   }
   return 0;
}
I=0 J=1
I=0 J=2
I=0 J=3
I=0.2 J=1.2
I=0.2 J=2.2
I=0.2 J=3.2
I=0.4 J=1.4
I=0.4 J=2.4
I=0.4 J=3.4
I=0.6 J=1.6
I=0.6 J=2.6
I=0.6 J=3.6
I=0.8 J=1.8
I=0.8 J=2.8
I=0.8 J=3.8
I=1 J=2
I=1 J=3
I=1 J=4
I=1.2 J=2.2
I=1.2 J=3.2
I=1.2 J=4.2
I=1.4 J=2.4
I=1.4 J=3.4
I=1.4 J=4.4
I=1.6 J=2.6
I=1.6 J=3.6
I=1.6 J=4.6
I=1.8 J=2.8
I=1.8 J=3.8
I=1.8 J=4.8
I=2.0 J=3.0
I=2.0 J=4.0
I=2.0 J=5.0

Alguém sabe por que o print dos 3 últimos sai errado ?

Remember not post solutions. Your post may be reviewed by our moderators.

  • Edivaldo Guimarães replied 1 year ago

    Usa double no lugar de float.

  • feodorv replied 1 year ago

    You see that .2 can't be precisely represented in float values. Seems that your value for the variable I is not 2.0 but 1.999999 so the comparison does not work. You can rewrite the code with only integer variables.