Algorithm C. Why does the string "Why" return and does not return numerical values?

Asked

Viewed 50 times

2

I wrote an algorithm in C to write on the screen ordered pairs of a function, with input of x integer numbers.

int main(int argc, char *argv[])
{
    int x,i;
    x = -1;

    do{
        system("cls");
        scanf("%i",&x);

        if(x>1000 || x <=0){
            printf("Entrada Invalida.");
            getch();
        }
    }while(x>1000 || x<=0);

    //scanf("%i",&x);
    float y[x];

    for(i=0;i<=x;i++){
        y[i]= pow(i,3) + pow(i,2) +i;
        printf("(%i,%.2f)\n",i,y[i]); 
    }
    system("PAUSE");    
    return 0;
}

I’ve put restrictions on entry, but the restrictions are just numerical. It turns out, with the previous code, if I type "Why" instead of a number, I get the expected result: "Invalid entry". But with the following code:

int main(int argc, char *argv[])
{
    int x,i;
    x = -1;
    //scanf("%i",&x);
    float y[x];

    for(i=0;i<=x;i++){
        y[i]= pow(i,3) + pow(i,2) +i;
        printf("(%i,%.2f)\n",i,y[i]); 
    }

    system("PAUSE");    
    return 0;
}

I get the following:

inserir a descrição da imagem aqui

Why does this happen? Why is the constraint, even if it is only numerical, the result is "Invalid entry"? Why when there is no constraint the program calculates values, even though the input is string("Why")?

1 answer

1


Your code is a little fuzzy, but I ran some tests and I figured out what’s going on. When you type "Why" in the first code it can assign the upper limit of integers which is 2 15-1 (32767) if you do not assign a value to X. This makes if true because 32767 > 1000.

Or as "Why" is an invalid value it keeps the value -1, which also makes if true because -1 <= 0.

The code I used to test:

#include <stdio.h>

int main(int argc, char* argv){

    int x; // Saídas: 32767, 32766, 32765 ...
    // int x = -1; Saídas: -1, -1, -1
    scanf("%i", &x);

    printf("%i\n", x);

    return 0;        
}

A good way to see how things happen is to use printf in different places to know how the values are going (or another more sophisticated debug strategy). Try to tidy up that code 'cause he didn’t come out this way.

  • Output of a program that reads an integer number and writes it as float: {Why --> 2686792.000000}. When typing "Why" it prints that number.

  • the first part of his answer clarifies the fact that the condition is respected. If "Why" is equivalent to 26786792 then it is greater than 1000. I tried to vote for your answer , but I only have 6 points on the site.

Browser other questions tagged

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