【发布时间】:2021-12-13 15:03:29
【问题描述】:
我的一个朋友用 C 编写了这个:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int number;
if (scanf("%d", &number) != 1) {
printf("ERROR: While reading the 'int' value an error occurred!");
return EXIT_FAILURE;
}
if (number == 0){ //if number is 0 then nothing to do!
printf("%d", number);
}
else{
char reverse[11]; //created a char array of len 11
int ind=0; //created int ind for array iteration!
while(number) // while loop with the number
{
int digit = number % 10; //calculate the digit that that will be in the first place in the char array
我想知道代码中的这一行是做什么的:
reverse[ind++] = digit + '0'; //add digit to array at ind position
我知道它将预先创建的数组中的数字设置在“ind”位置,然后递增“ind+1”,但我不知道 + '0' 的作用。
number = number / 10; //cut the number so that we get the new number
}
reverse[ind]='\0';
printf("%s\n",reverse);
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
+ '0'将零字符的值添加到数字。假设数字的字符是连续的并且按升序排列,这会将数字(从零到九的数字)转换为对应于该数字的字符代码(例如,ASCII 中从 48 到 57 的数字)。