Issue
So, with my beginner level of experience in C I've been trying to write a code that converts hexadecimal input to a decimal with an array. I believe you will get it more spesificly by looking at my code but it does not work properly. I keep getting an amount that is much larger than intended.
#include <stdio.h>
int main()
{
int i, k, j, N, power, result;
char array[50];
result = 0;
printf("how many charecters are there in your hexadecimal input?: \n");
scanf("%d", &N);
for(k=0; k<=N-1; k++)
{
printf("What is the %d . value of your hexadecimal input?: \n", k+1);
scanf("%s", &array[k]);
}
for(i=0; i<=N-1; i++)
{
power = 1;
for(j=0; j<=i; j++)
{
power = power *16;
}
if((array[i] >= 0) && (array[i] <= 9))
{
result = result + array[i] * power;
}
else
{
result = result + (array[i] - 'A' + 10) * power;
}
}
printf("your result is %d", result);
return 0;
}
Solution
just edited your code a little bit, and also the input is supposed to be from left to right instead of right to left according to which I think you have coded. Hence, for C6, first C then 6.
#include <stdio.h>
int main()
{
int i, k, j, N, power, result;
char array[50];
result = 0;
printf("how many charecters are there in your hexadecimal input?: \n");
scanf("%d", &N);
for(k=0; k<=N-1; k++)
{
printf("What is the %d . value of your hexadecimal input?: \n", k+1);
scanf(" %c", &array[k]);
}
for(i=0; i<=N-1; i++)
{
power = 1;
for(j=0; j<=N-2-i; j++)
{
power = power*16;
}
if((array[i] >= '0') && (array[i] <= '9'))
{
result = result + (array[i] - '0') * power;
}
else
{
result = result + (array[i] - 'A' + 10) * power;
}
}
printf("your result is %d", result);
return 0;
}
the takeaways
- your input taking is inefficeient. and in that too %c instead of %s in scanf.
if((array[i] >= 0) && (array[i] <= 9))
, suppose i=1 and array[1] = 7. Now, you are comparing ascii value of 7 which is 55, instead of 7.- same thing in the statement of if, the ascii values of array[i] are being used so I have subtracted accordingly.
Answered By - mr.loop Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.