为什么我通过两个短整数相乘得到负数?
问题说明
我有一个任务,我有以下代码摘录:
I had an assignment where i had the following code excerpt:
/*OOOOOHHHHH I've just noticed instead of an int here should be an *short int* I will just left it as it is because too many users saw it already.*/
int y=511, z=512;
y=y*z;
printf("Output: %d
", y);
这给了我输出:-512
.在我的作业中,我应该解释原因.所以我很确定这是因为将 int
值分配给短整数时发生的隐式转换(如果我错了,请纠正我:)).但是我的导师说这件事刚刚发生,我猜它被称为三轮".我找不到任何关于它的信息,我正在观看这个 视频 那家伙解释(25:00)几乎和我告诉我的导师一样的事情.
Which gives me Output: -512
. In my assignment I should explain why. So i was pretty sure it is because of the implicit conversion( correct me if I'm wrong:) ) happening from assigning an int
value to an short int. But my tutor said that thing just happened called something with "triple round" i guess. I couldn't find anything about it and I'm watching a this video and the guy explains(25:00) almost the same thing I told my tutor.
这是我的完整代码:
#include <stdio.h>
int main() {
short int y=511, z=512;
y = y*z;
printf("%zu
", sizeof(int));
printf("%zu
", sizeof(short int));
printf("Y: %d
", y);
return 0;
}
我是这样编译的:
gcc -pedantic -std=c99 -Wall -Wextra -o hallo hallo.c
我没有收到任何错误和警告.但是如果我在启用 -Wconversion 标志的情况下编译它,如下所示:
I get no errors and no warnings. But if i compile it with -Wconversion flag enabled as follows:
gcc -pedantic -std=c99 -Wall -Wextra -Wconversion -o hallo hallo.c
我收到以下警告:
hallo.c: In function ‘main’:
hallo.c:7:7: warning: conversion to ‘short int’ from ‘int’ may alter its value [-Wconversion]
所以转换确实发生了?
正确答案
int
到 short int
的转换是实现定义的.您得到结果的原因是您的实现只是截断了您的数字:
The conversion from int
to short int
is implementation defined. The reason you get the result you do is that your implementation is just truncating your number:
decimal | binary
----------- ------------------------
511 | 1 1111 1111
512 | 10 0000 0000
511 * 512 | 11 1111 1110 0000 0000
由于您似乎具有 16 位 short int
类型,因此 11 1111 1110 0000 0000
变成了 1111 1110 0000 0000
,这是 -512
的二进制补码表示:
Since you appear to have a 16-bit short int
type, that 11 1111 1110 0000 0000
becomes just 1111 1110 0000 0000
, which is the two's complement representation of -512
:
decimal | binary (x) | ~x | -x == ~x 1
--------- --------------------- --------------------- ---------------------
512 | 0000 0010 0000 0000 | 1111 1101 1111 1111 | 1111 1110 0000 0000
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangcbjff
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20