使用 n[c-'0'] 的真正用途是什么? [英] What's the real use of using n[c-'0']?

查看:35
本文介绍了使用 n[c-'0'] 的真正用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 的新手,我遇到了这样的代码:

I'm a novice in C and I came across the code like this :

int n[10];
if(c>='0' && c<='9')
++n[c-'0']

if循环中为什么我们必须在0周围使用单引号,它的用途是什么,为什么我们不能定义0直接作为整数?而在第二行代码++n[c-'0']中,像这样使用数组有什么用,为什么我们需要减去0(再次为什么在这种情况下使用单引号?)来自 c 在数组索引中?

In if loop why we have to use single quotes around 0, whats the use of it, why we can't define 0 as an integer straight away? And in the second line of code ++n[c-'0'], whats the use of using array like this, in sense why we need to subtract 0(once again why the use of single quotes in this context?) from c in the array index?

如果我喜欢这个n[c-'0'],索引操作(c-'0') 的结果是字符还是整数?

If i do like this n[c-'0'], the result of index operation(c-'0') will be an character or integer?

既然如此,谁能告诉我,这种数组的真正用途是什么,它的缺点是什么?

Given that can anyone say me, whats the real use of such array and what are the disadvantages well?

提前致谢.

推荐答案

在 C 中,'0' 是一个整数,其值将数字零表示为字符,而不是值 0,这将为空字符.其他答案省略了这一点,但需要注意的是,C 语言要求十进制数字具有连续值,因此如果 c 是数字,c-'0' 是那个数字的数值,即

In C, '0' is an integer whose value represents the digit zero as a character, not the value 0, which would be the null character. Other answers have omitted this, but it's important to note that the C language mandates that the decimal digits have consecutive values, so that if c is a digit, c-'0' is the numeric value of that digit, i.e.

'0'-'0' = 0
'1'-'0' = 1
'2'-'0' = 2
.
.
.
'9'-'0' = 9

这篇关于使用 n[c-'0'] 的真正用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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