简体   繁体   English

在 C 中以 IEEE 标准打印浮点数(十六进制)

[英]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).我想以 IEEE 标准表示(符号、8 位指数、23 位尾数)打印两个浮点数的十六进制值。 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. 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;
}

In the absence of flow control, C runs from top to bottom.在没有流控的情况下,C从上到下运行。 So when you initialize RandomVector using two uninitialized variables, you get Undefined Behavior.因此,当您使用两个未初始化的变量初始化RandomVector时,您会得到未定义的行为。 It does not matter that you later assign two values to Vector 1 and Vector2 .稍后将两个值分配给Vector 1 和Vector2

Your RandomVector is random in the sense that it is based on uninitialized values, which is undefined behavior.您的RandomVector是随机的,因为它基于未初始化的值,这是未定义的行为。 You only assign values to Vector1 and Vector2 after that, but you never use those.之后你只为Vector1Vector2 ,但你从不使用它们。 You should try it like this:你应该这样尝试:

float RandVectorGen (void)
{
    unsigned int Vector1, Vector2;
    float RandomVector;

    Vector1 = (rand() % 30);
    Vector2 = (rand() % 30);
    
    RandomVector = ((float)Vector1 / (float)Vector2) * fabs(sin(rand() % 10));

    return RandomVector;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM