• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助5

问题说明

我有一个任务,我有以下代码摘录:

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] 

所以转换确实发生了?

正确答案

#1

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tangcbjff
系列文章
更多 icon
同类精品
更多 icon
继续加载