我正在实现一个程序,在C中将十六进制数转换为十进制,但我的程序无效。请帮助我让程序正常运行。
我不知道该程序的哪个部分有bug。任何建议和答案都会有所帮助。
代码:
#include <stdio.h>
#include <math.h>
char hexNum[100];
int getDecimal();
int main(int argc, char **argv) {
printf("Enter the hex number: ");
int i = 0;
char ch;
while ((ch = getchar()) != '\n') {
hexNum[i++] = ch;
}
hexNum[i] = '\0';
printf("\nHexadecimal Number is: %s", hexNum);
int n = getDecimal();
printf("\nDecimal Number is: " + n);
return 0;
}
int getDecimal() {
//get to the units digit index
int index = 0;
while (hexNum[index + 1] != '\0') {
index++;
}
//calculate the decimal value and store the result in result var
int var = 0; //store the decimal number
int exp = 0; //keep track of exponent of 16^x
while (index >= 0) {
int ch = hexNum[index--];
switch (ch) {
case 'a':
var = var + (10 * pow(16, exp++));
break;
case 'b':
var = var + (11 * pow(16, exp++));
break;
case 'c':
var = var + (12 * pow(16, exp++));
break;
case 'd':
var = var + (13 * pow(16, exp++));
break;
case 'e':
var = var + (14 * pow(16, exp++));
break;
case 'f':
var = var + (15 * pow(16, exp++));
break;
default: //if its a digit
var = var + ((ch-'0') * pow(16, exp++));
break;
}
}
return var;
}
答案 0 :(得分:1)
更改此行:
printf("\nDecimal Number is: " + n);
到
printf("\nDecimal Number is: %d\n", n);
此外,您的算法太复杂,性能也很差。
最好使用前向迭代而不是后向迭代。类似的东西:
var = 0;
index = 0;
while (hexNum[index] != '\0')
{
var = 16 * var;
switch (hexNum[index]) {
case 'a':
var = var + 10;
break;
case 'b':
var = var + 11;
break;
... and so on ...
}
++index;
}
return var;
答案 1 :(得分:0)
例如'12'你计算1 * pow(16,0)+ 2 * pow(16,1)这可能是 不是你想要的,除非你想在反向顺序中输入数字......
答案 2 :(得分:0)
char *ValidationNumber(char *value)
{
char *ptr=NULL;
if(isdigit(*value)){
ptr=valor;
///ptr=(int*) value;
}
return ptr;
}
char *ptr,c;
int main(int argc, char *argv[]){
printf("Enter number: %i ");
scanf("%i");
ptr=&c;
if(ValidatioNumber(ptr) !=NULL){
printf("Valid value: %i");
}else
printf("Input invalid");
system("PAUSE");
return EXIT_SUCCESS;
}