Why do I get a negative number by multiplying two short ints?(为什么我通过将两个短整数相乘得到一个负数?)
问题描述
我有一个任务,我有以下代码摘录:
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
这篇关于为什么我通过将两个短整数相乘得到一个负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我通过将两个短整数相乘得到一个负数?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01