Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- const char* Labels[]={"Inf","NaN","12 "};
- #define SIZE 6
- #define NEG12 5
- #define POS12 4
- #define NEGNAN 3
- #define POSNAN 2
- #define NEGINF 1
- #define POSINF 0
- void print(const char*,const float*,const int*);
- /*Testing what invalid numbers look in float*/
- int main(int argc,char* argv[])
- {
- /*we want to store 6 float values (infinity, -Infinity, NaN, -NaN, 12, -12)*/
- float f[SIZE];
- /*
- This is a dirty trick, we create an integer array,
- that is in the same location as the float array.
- This allows us to look at the floats as integers.
- Floats and integers are both 32bit, so they occupy
- the same number of bytes in memory (4)
- */
- int* i=(int*)&f;
- /*Positive Infinity*/
- f[POSINF]=1.0/0.0;
- /*Negative Infinity*/
- f[NEGINF]=-1.0/0.0;
- /*NaN from positive Infinity*/
- f[POSNAN]=f[POSINF]-f[POSINF];
- /*NaN from negative Infinity*/
- f[NEGNAN]=f[NEGINF]-f[NEGINF];
- /*Regular positive number*/
- f[POS12]=12.0;
- /*Regular negative number*/
- f[NEG12]=-12.0;
- print("Values 'as-is'",f,i);
- /*test what happens, if we copy NaN over the positive infinity, but use integers*/
- i[POSINF]=i[POSNAN];
- print("Copy +NaN (int) to +Inf (int)",f,i);
- /*Assigning the NaN integer to a float*/
- f[NEGINF]=(float)i[POSNAN];
- print("Assigning +NaN (int) value to -Inf (float), but cast it correctly",f,i);
- /*Assigning -12 directly to a float via integer*/
- i[NEG12]=-12;
- print("Assigning -12 (int) to -12 (float) by setting the int value",f,i);
- /*END*/
- printf("\r\nPress return to exit\r\n");
- getchar();
- return 0;
- /*
- Conclusion:
- - Inifinity and NaN are just specific numbers.
- - Infinity exists as positive and negative
- - NaN exists only as a negative number
- - Floats have a protection against accidental assignment of said invalid value (crash proof)
- - Floats store numbers completely differently from integers
- */
- }
- /*prints table of numbers*/
- void print(const char* description,const float* f,const int* i)
- {
- int q=0;
- printf("\r\n%s\r\n\r\nFLOAT---------------- INT------------------\r\n",description);
- for(q=0;q<SIZE;q++)
- {
- char c=q%2==0?'+':'-';
- printf("%c%s: %15f %c%s: %15i\r\n",
- c,Labels[q/2],
- f[q],
- c,Labels[q/2],
- i[q]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement