为什么我通过将两个短整数相乘得到一个负数?

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] 

所以转换确实发生了?

推荐答案

intshort 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

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

本文标题为:为什么我通过将两个短整数相乘得到一个负数?

基础教程推荐