我的一個朋友用 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;
}
uj5u.com熱心網友回復:
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 = '<n>'。 - 對于十六進制數字,您可以使用:
char digit = "0123456789ABCDEF"[n]
uj5u.com熱心網友回復:
char也只是數字。
根據使用的字符集,每個數字都被分配給一個特定的字符。
您可以查看ASCII 代碼表以了解哪些數字對應于哪些字符。
0-9andA-Z和a-z是有序的,這對于映射數字非常有用。
所以 0-9 將是:
| 特點 | 數值 |
|---|---|
| 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/340808.html
上一篇:為什么我的映射回傳太多條目?
