【问题标题】:C reverse number with print and arrayC反向数字与打印和数组
【发布时间】: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 的数字)。

标签: arrays c string


【解决方案1】:

char 也只是数字。
根据所使用的字符集,每个数字都被分配给一个特定的字符。

你可以看一下ASCII Code Table,看看哪个数字对应哪个字符。

0-9A-Za-z按顺序排列,这对于映射数字非常有用。

所以 0-9 将是:

Character Numeric Value
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57

因此,将 0-9 之间的数字添加到 '0' 将产生与该数字等效的 ascii 字符,例如:

assert('0' == '0' + 0);
// ...
assert('5' == '0' + 5);
// ...
assert('9' == '0' + 9);

这也适用于字母:

assert('A' == 'A' + 0);
assert('J' == 'A' + 9);
assert('Z' == 'A' + 25);

同样也可以通过反转输入来完成,而无需先解析数字:

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

int main(void) {
    char buf[256];
    if(!fgets(buf, sizeof(buf), stdin))
        return 0;
    for(int i = 0, len = strlen(buf); i < len / 2; i++) {
        char tmp = buf[i];
        buf[i] = buf[len-1-i];
        buf[len-1-i] = tmp;
    }
    puts(buf);
    return 0;
}

如果你的标准库包含strrev,它会更短:

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

int main(void) {
    char buf[256];
    if(!fgets(buf, sizeof(buf), stdin))
        return 0;
    strrev(buf);
    puts(buf);
    return 0;
}

【讨论】:

    【解决方案2】:
    • reverse 是一个字符数组 (char[11])
    • 所有标准 C 函数都使用 ASCII 表将数字表示为 字符(每个字符都有自己的编号),对于字符'0''1''2''3''4''5''6''7''8''9' 值 分别是:48、49、50、51、52...
    • 因此如果你加 48 + 1 ('0' + 1) 你得到 49 对应于'1',所以通常是十进制 数字:'0' + n = '&lt;n&gt;'
    • 对于十六进制数字,您可以使用:char digit = "0123456789ABCDEF"[n]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 2013-07-08
      • 2017-08-26
      • 2013-12-16
      相关资源
      最近更新 更多