为什么我将两个短整数相乘得到一个负数? [英] Why do I get a negative number by multiplying two short ints?

查看:107
本文介绍了为什么我将两个短整数相乘得到一个负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作业,其中有以下代码摘录:

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\n", 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\n", sizeof(int));
    printf("%zu\n", sizeof(short int));

    printf("Y: %d\n", 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] 

那么转换的确发生了吗?

So the conversion does happen right?

推荐答案

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位的短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

这篇关于为什么我将两个短整数相乘得到一个负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆