4
 #include <iostream> // cin, cout
using namespace std;
int main(void)
{
char c[80];
int i, sum=0;
cin.getline(c,80);
for(i=0; c[i]; i++) // c[i] != '\0'
if('0'<=c[i] && c[i]<='9') sum += c[i]-'0';
cout<< "Sum of digits = " << sum << endl;
getchar();
getchar();
return 0;
}

我明白一切都接受 sum += c[i] - '0'; 我删除了“-'0'”,但它没有给我正确的答案。为什么是这样?

4

4 回答 4

10

这会将字符从其字符代码(例如 ASCII 中的 48)转换为其等效整数。因此,它将字符'0'转换为整数值 0。正如 Pete Becker 在 C 和 C++ 语言定义的评论中指出的那样,要求所有数字字符都是连续的。

于 2013-03-20T09:36:00.417 回答
1

The ascii value for 0 is 48, for 1 its 49 and so on. Now in your program c[80] is an array of characters. So if you input 1 from the keyboard, the compiler treats it as 49 (the ascii value) for the arithmetic operation. That's why we need to subtract the ascii value of 0 (i.e 48) to get the integer equivalent. this can be achieved either by subtracting '0' from the character or by subtracting 48 directly. e.g. if you replace sum += c[i]-'0'; by sum += c[i]-48;, the code will also work. But this is not a good practice. Hope this helps.

于 2013-03-20T09:47:49.350 回答
1

'0' 返回 ASCII 值 0。因此,要使用数字而不是它们的 ASCII 值,您需要偏移 ASCII 值 0。'1' - '0' ::= 49 - 48 ::= 1 ( 49 和 48 分别是 1 和 0 的 ASCII 值)。

于 2013-03-20T09:38:34.150 回答
1

它将一个字符转换为整数值:

character | ASCII code  | expression | equivalent | result
  '0'     |      48     | '0' - '0'  |  48 - 48   |   0
  '1'     |      49     | '1' - '0'  |  49 - 48   |   1
  '2'     |      50     | '2' - '0'  |  50 - 48   |   2
  '3'     |      51     | '3' - '0'  |  51 - 48   |   3
  '4'     |      52     | '4' - '0'  |  52 - 48   |   4
  '5'     |      53     | '5' - '0'  |  53 - 48   |   5
  '6'     |      54     | '6' - '0'  |  54 - 48   |   6
  '7'     |      55     | '7' - '0'  |  55 - 48   |   7
  '8'     |      56     | '8' - '0'  |  56 - 48   |   8
  '9'     |      57     | '9' - '0'  |  57 - 48   |   9
于 2013-03-20T09:41:13.240 回答