我在这里试图将4位数的六草转换为DEC但没有成功。 这是我的代码。

unsigned int array[4];                         

printf("Type in 4-digit hexa: \n");

scanf("%x", &array);

while(getchar() != '\n');

printf("Your number in dec is %u \n", array);
.

我不知道它有什么问题,但它只是不会透露出正确的DED输出。 就像我进入Eff时,它应该发出61183,但程序在打印出65518.

这个数字来自哪里?我的代码有什么问题?我使用未签名的int根据我的考虑,FFFF等于65385,无符号int的范围是0到65535.数据范围应该没有问题,我也使用%u。 我在完成一些搜索后,我唯一可以想到的是,这个问题可能有没有与int的int或sth的大小。 我读了解释,但不太明白。

我知道,这可能是一种重复,但我在这里要求更容易解释 为什么这不起作用。要诚实,我是这个网站和编程的绝对纽比,所以请在编码上轻松进入我。 Fyi,我真的不知道在stdio.h之外的任何东西。

有帮助吗?

解决方案

You are passing a pointer, array, to printf(). There is no need for an array here, what you're trying to scan and print is a single number.

unsigned int number;

printf("Type in 4-digit hex:\n");

if (scanf("%x", &number) == 1)
  printf("Your number in dec is %u \n", number);

Also note that it's considered a good idea to check if scanf() succeeds or not, by inspecting the return value.

其他提示

You don't need an array for that:

unsigned int val;
printf("Type in 4-digit hexa: \n");
scanf("%x", &val);
printf("Your number in dec is %u \n", val);

a. print array[0], not array.

(optional) b. scan to array, not to &array.

c. what is the point of the getchar()?

No, you must input as string to a point of characters. After that, you convert to number. Ex

char *str=char[10];
int i=0,num=0;
printf("Type in 4-digit hexa: ");
scanf("%s",str);

for(i=0;str[i]!='\0';i++)
   if(str[i]>='0' && str[i]<='9') num=16*num+str[i]-'0';
   else if(str[i]>='a' && str[i]<='f') num=16*num+str[i]-'a';
   else if(str[i]>='A' && str[i]<='F') num=16*num+str[i]-'A';

printf("Dec is %d",num);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top