在c中将2个字符加在一起的问题 [英] problems adding 2 characters together in c

查看:81
本文介绍了在c中将2个字符加在一起的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在c中添加2个字符,即

I'm currently trying to add 2 characters in c i.e.

char a = 127;
char b = 127;
char c = a + b;

printf("%d\n", c);

打印出4294967278,我每次将两个数字相加而得到的ASCII码时实际上都遇到了问题值将大于127,这是怎么回事?字符不是8位还是256个可能的数字?

which prints out 4294967278, I'm actually having problems anytime I add 2 numbers together where the resultant ASCII value would be greater than 127, what is happening here? aren't characters 8 bits or 256 possible numbers? so adding values that would be less than 256 should work no?

推荐答案

可能是因为您的 char 签名的,可以保存-128到127之间的值。通过使用

Probably because your chars are signed and can hold values from -128 to 127. By using

char c = a + b;

您有一个溢出的签名字符导致未定义行为。您可以使用 unsigned char 来解决此问题:

you have an overflow and overflow of signed char results in Undefined Behavior. You can use an unsigned char to get rid of the problem:

unsigned char c = a + b;

这篇关于在c中将2个字符加在一起的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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