未如预期一个简单的C程序的输出 [英] A simple C program output is not as expected

查看:62
本文介绍了未如预期一个简单的C程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做这个简单的程序和我的脑海里卡住了。

 #包括LT&;&stdio.h中GT;    诠释的main()
    {
        int类型的签署;
        符号字符℃;
        unsigned char型B:
        B = 0xF4中;
        A =(签字)B: // 1)这个任务应该是相同的
        C =(签字)B:
        的printf(%d个\\ N,一);
        一个= C; // 2)这一个
        的printf(%d个\\ N,一);
        返回0;
    }一个= 244,A = -12

我试过,以确保任务是顺利,因为它可以,但我得到两个不同的答案,我希望无论是作为-12。什么小东西我丢失?


有关问题是

  {
    B = 0xF4中;
    C = 0xF4中;
    A =(符号的int)B: //试图挽救迹象,但得到244
    的printf(%d个\\ N,一);
    一个= C; // SIGN保存在这里,并得到-3
    的printf(%d个,一);
}

244,-3

所以我想从unsigned char类型保存迹象。这是可能以这种方式?


解决方案

 符号字符℃;
    unsigned char型B:
    B = 0xF4中;    / * ... * /    C =(签字)B:

的值是 0xF4中 244 ),但 C 键入(符号字符)只能容纳 -128 127 (在你的实现)。因此,当 244 分配给 C ,先把它转化为符号字符和C表示这个整数的转换是实现定义。 GCC 为大多数实现
只是环绕模 256 ,这就是为什么的ç值为 -12

下面是 GCC 文件:

http://gcc.gnu.org/onlinedocs/gcc/Integers- implementation.html


  

对于转换的类型的宽度N的值减小模2 ^ N至是内的类型的范围


I was doing this simple program and my mind got stuck

    #include<stdio.h>

    int main()
    {
        signed int a;
        signed char c;
        unsigned char b;
        b = 0xf4;
        a = (signed)b;       //    1)this assignment should be same 
        c = (signed)b;
        printf("%d\n",a);
        a = c;              //     2)as this one
        printf("%d \n",a);
        return 0; 
    }

a = 244, a = -12

I tried to make sure that assignment is as smooth as it can be but I am getting two different answers and I expected both as -12. What small thing I am missing?


The relevant question was

{
    b = 0xf4;
    c = 0xf4;
    a = (signed int)b;           //trying to save sign but get 244 
    printf("%d\n", a);
    a = c;                       //sign saved here and got -3 
    printf("%d", a);
}

244, -3

so i am trying to save the sign from an unsigned char. Is this possible in this manner?

解决方案

    signed char c;
    unsigned char b;
    b = 0xf4;

    /* ... */

    c = (signed)b;

The value of b is 0xf4 (244) but c type (signed char) can only hold values between -128 and 127 (in your implementation). So when 244 is assigned to c it is first converted to signed char and C says this integer conversion is implementation defined. gcc as most implementations just wraps around modulo 256 and that's why the value of c is -12.

Here is gcc documentation:

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

"For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type"

这篇关于未如预期一个简单的C程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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