One variable, two different results.

2

One question, why when I print the variable 'Age' does the result come out first well, and then multiplied by 10?

Code:

int main ()
{

    int Beca, Edad;
    float Prom;
    char edad[2], beca; 
    int valid; 

        do
       {        
            valid = 1;
            printf ("\n Digite la edad: ");
            scanf("%2s",&edad);

            int len = strlen(edad);
            int potencias[2] = {1,10};
            printf("\nAntes del for: %d", Edad);
            for(int i = 0; i<len; i++){
                printf("\n Dentro del for %d: %d", i, Edad);

                if(isdigit(edad[i])) {
                    Edad += (edad[i]-'0') * potencias[len-i-1]; 
                    printf("\n Dentro del if: %d", Edad);
                    }else{
                        printf("No es un numero");
                        valid = 0;
                    }
                }

            if (Edad==0 || Edad>=70){
                printf("\n ENTRE ");
                printf ("\n Digite una edad valida\n\n");
                valid = 0;
            } 
            printf("\nDESPUES DEL FOR %d", Edad); 
            printf("\nDESPUES DEL FOR %d", Edad);
        }while (valid == 0);    
       // Más código 
    }

* The extra printf were for testing. Thanks in advance!

    
asked by Adalgisa Ferrer 02.08.2017 в 23:51
source

1 answer

2
char edad[2]; 
scanf("%2s",&edad);

If you use scanf with %s , the function will end the string with a null character. That is, to store "14" you will need 3 spaces ... and your variable only supports 2. The result is that you are stepping on the value of another variable. which one? It depends on the compiler and the optimizations you make. In some cases you can even work and in others will give you the most varied mistakes.

If you assume that the age is valid in the range (1-99), then you will have to use a variable with a minimum of 3 holes:

char edad[3];
    
answered by 03.08.2017 / 00:08
source