Gabbed
Gabbed

Reputation: 37

Printing floating-point numbers (hexadecimal) in IEEE standard in C

I want to print the hexadecimal value of two floating point numbers in the IEEE standard representation (sign, 8 bit exponent, 23 bit mantissa). My problem is that the numbers that I random generate are super big (for example: -26815622280406798000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000) without any numbers after the point (only 0) and with sign.

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

float RandVectorGen(void);

int main () {

    srand(time(NULL));

    float Vectors_A = 0, Vectors_B = 0, Vectors_SUM = 0; 

            for(int i = 0; i <= 20; ++i) {
                
                Vectors_A = RandVectorGen();      //Genera 20 vettori tra 100 e 0
                Vectors_B = RandVectorGen();

                printf("Vettore %d_A: %x  =>  %.6f\n", i, Vectors_A, Vectors_A);
                printf("Vettore %d_B: %x  =>  %.6f\n", i, Vectors_B, Vectors_B);

                Vectors_SUM = Vectors_A + Vectors_B;            

                printf("Somma tra i due vettori: %x  =>  %.6f\n", Vectors_SUM, Vectors_SUM);

                puts(" ");

                }

    return 0;

}

float RandVectorGen (void) {

    
    unsigned int Vector1, Vector2;
    float RandomVector = ((float)Vector1 / (float)Vector2) * fabs(sin(rand() % 10));

        Vector1 = (rand() % 30);
        Vector2 = (rand() % 30);

    return RandomVector;
}

Upvotes: 0

Views: 177

Answers (1)

MSalters
MSalters

Reputation: 179897

In the absence of flow control, C runs from top to bottom. So when you initialize RandomVector using two uninitialized variables, you get Undefined Behavior. It does not matter that you later assign two values to Vector1 and Vector2.

Upvotes: 2

Related Questions