将十六进制扫描 (scanf) 从无符号 int 数组转换为十进制
我在这里尝试将 4 位十六进制转换为十进制,但没有成功。 这是我的代码。
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);
我不知道它出了什么问题,但它只是不会给出正确的 dec 输出。 就像当我输入 EEFF 时,它应该给出 61183,但程序继续打印出 65518。
这个数字是从哪里来的?我的代码有什么问题吗?我根据自己的考虑使用了unsigned int,FFFF等于65385,unsigned int的范围是0到65535。数据范围应该没有问题,我也用了%u。
在完成一些搜索后,我现在唯一能想到的是这个问题可能与 unsigned int 到 int 或 sth 的大小有关。 我读了解释但不太明白。
我知道,这可能是重复的,但我在这里寻求更简单的解释 为什么这不起作用。老实说,我对于这个网站和编程来说都是一个绝对的新手,所以请在编码方面对我放轻松。仅供参考,我真的不知道 stdio.h 之外的任何东西。
I'm here trying to convert 4-digit hexa into dec but didn't succeed.
Here is a my code.
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);
I don't know what's wrong with it but it just wouldn't give out the correct dec output.
Like when I put in EEFF, it's supposed to give out 61183 but the program kept on printing out 65518.
Where's this number from? What's wrong with my code? I used unsigned int according to my consideration that FFFF is equals to 65385 and the range for unsigned int is 0 to 65535. There should be no problem with the range of data and I also used %u with it.
The only thing I can think of right now after I've done some searching is that this problem might has sth to do with the size of unsigned int to int or sth.
I read the explanation but didn't quite understand.
I know, this might be a duplication but I'm here asking for an easier explanation
of why this doesn't work. To be honest, I'm an absolutely newby for both this site and programming so please go easy on me with the coding. FYI, I don't really know anything outside of stdio.h .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在将指针
数组
传递给printf()
。这里不需要数组,您要扫描和打印的只是一个数字。另请注意,通过检查返回值来检查
scanf()
是否成功被认为是一个好主意。You are passing a pointer,
array
, toprintf()
. There is no need for an array here, what you're trying to scan and print is a single 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:
一个。打印
array[0]
,而不是array
。(可选)b.扫描到
array
,而不是&array
。c.
getchar()
的意义是什么?a. print
array[0]
, notarray
.(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