In: Computer Science
Write a C Program to finish the following requirements: Convert a double number to its hexadecimal form
1. The double number x is located between 0 and 1000(0<=x<=1000),e.g.678.345
2.The double number with the hexadecimal form contains 6 significant digits. e.g." 5D.32FA45".
3.The double number with the hexadecimal form is represented by a string(or a character array), e.g."5D.32FA45".
Please write as simple as possible because I am a freshman in C! And please give me some clues!
Thanks!
Code:
#include <stdio.h>
#include <string.h>
int main()
{
double x;
printf("Enter the value of x: ");
scanf("%lf", &x);
char hex[30];
snprintf(hex, sizeof(hex), "%A", x); //saving hex equivalebt to hex
char hexFormat[30]; //creating new char array hexFormat to print hex in proper Format
int i, index1 = 0, index2 = 0;
//to find position of '.' or end of hex value
for(i=0; i < strlen(hex); i++)
{
if(hex[i] == '.')
index1 = i;
if(hex[i] == 'P')
index2 = i;
}
//saving to hexFormat
if(index1 != 0)
for(i=2; i < index1+7; i++)
hexFormat[i-2] = hex[i];
else
for(i=2; i < index2; i++)
hexFormat[i-2] = hex[i];
hexFormat[i-2] = '\0';
printf("Hex equivalent of x = %s\n\n", hexFormat);
}
Output: