请解释这个代码正在做什么(someChar - 48) [英] Please explain what this code is doing (someChar - 48)

查看:230
本文介绍了请解释这个代码正在做什么(someChar - 48)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一些练习问题,我看到这段代码:

I'm going through some practice problems, and I saw this code:

#include <stdio.h>
#include <string.h>

int main(void) {
   char* s = "357";
   int sum = 0;
   int i = 0;
   for (i = 0; i < strlen(s); i++) {
     sum += s[i] - 48;
   }
   printf("Sum is %d", sum);

   return 0;
}

/ p>

Can someone explain what the code does, especially the subtraction with 48 part?

推荐答案

代码基本上总和表示为字符串的数字的数字。它使两个重要的假设正常工作:

The code basically sums the digits of a number represented as a string. It makes two important assumptions to work properly:


  • 字符串只包含'0'中的字符' 9'范围

  • 使用的字符编码是ASCII

在ASCII中,'0'== 48 '1'== 49 等等。因此,'0' - 48 == 0 '1' - 48 == 1 等等。也就是说,减去48将 char '0'..'9'转换为 int value 0..9

In ASCII, '0' == 48, '1' == 49, and so on. Thus, '0' - 48 == 0, '1' - 48 == 1, and so on. That is, subtracting by 48 translates the char values '0'..'9' to the int values 0..9.

因此,正是因为'0'== 48 ,代码也可以使用:

Thus, precisely because '0' == 48, the code will also work with:

sum += s[i] - '0';

此版本的意图可能略微更清楚。

The intention is perhaps slightly more clear in this version.

您当然可以通过添加进行反向映射,例如 5 +'0'=='5'。同样,如果您在'A'..'Z'范围内包含一个字母 char ,则可以减去'A',以获取 0..25 范围内该字母的索引。

You can of course do the "reverse" mapping by addition, e.g. 5 + '0' == '5'. Similarly, if you have a char containing a letter in 'A'..'Z' range, you can "subtract" 'A' from it to get the index of that letter in the 0..25 range.

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