Show value of a struct

3

I'm having a problem that is probably silly but I do not understand why it does not work despite its simplicity.

Having a struct composed of the components of a vector in 3D, I only wanted to show one of them after I typed it and yet it shows me a gigantic value:

struct vector3D
{
    double x, y, z;
};

int main()
{
    vector3D v;

    printf("Introduce las tres componentes de un vector3D");
    printf("\nComp. 1: ");   scanf("%f", &v.x);
    printf("Comp. 2: ");   scanf("%f", &v.y);
    printf("Comp. 3: ");   scanf("%f", &v.z);

    printf("%f", v.x); // Aquí muestra un valor que no tiene nada que ver con lo 
                       // que he tecleado previamente y me impide hacer otros cálculos

return 0;
}

I do not know if I have declared something wrong or what. I appreciate your attention. Greetings.

    
asked by Laura 23.01.2018 в 13:46
source

2 answers

3

As it has not been specified if the language is C or C ++, I go with both: ^)!

As such, the code you give us should not compile (In C) , or at least, throw out about 8 warnings and about 3 errors (Eh I said the numbers of head) .

To start, you use printf and scanf without having made a #include <stdio.h> (For ) or a #include <cstdio> (For ) .

Part of the answer for

answered by 23.01.2018 в 14:24
3

If you're programming in C ++, do not use printf or scanf but cin and cout :

int main()
{
    vector3D v;

    std::cout << "Introduce las tres componentes de un vector3D\n";
    std::cout "Comp. 1: ";
    std::cin >> v.x;
    std::cout "Comp. 2: ";
    std::cin >> v.y;
    std::cout "Comp. 3: ";
    std::cin >> v.z;

    std::cout << v.x;

    return 0;
}

But ... why does it fail?

As @NaCl tells you, the problem occurs because you are setting scanf to read float instead of double ... How important is this little detail?

Well, let's see:

  • double has 52 mantissa bits, 11 exponent bits and 1 sign bit .
  • float has 23 mantissa bits, 8 exponent bits and 1 sign bit.

Expressed graphically, it would look like this:

float   S E E E E E E E E M M M M M M M M M M M M M M M M M M M M M M M
double  S E E E E E E E E E E E M M M M M M M M M M M M M M M M M M M M M M M M M ..... M

So, if you store in double a data float without making conversions, the following happens:

float   0 1 1 0 0 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1
double  0 1 1 0 0 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 M M M M M ..... M

Note that the remaining M of double do not see their value altered and they will contain garbage ... which is what distorts the result obtained when printing the return number.

So, as I mentioned right away, start the answer ... if programs in C ++ make use of the characteristics of C ++.

    
answered by 23.01.2018 в 14:35