所以我被指派用 c 語言存盤兩個 50 位整數,并使用它們做數學方程。我的問題是將輸入的數字逐位存盤在陣列中。我想我可以將輸入存盤在這樣的字符字串中:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
return 0;
}
但是我不能將它用作數字,因為它被存盤為 char 并且我無法將它們逐位復制到另一個定義為 int 的陣列中
經過一整天的搜索,我發現我需要像這樣一個一個地復制我的字串:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
int arr[50];
for (int i = 0; i < 50; i )
{
arr[i] = string_test[i] - '0';
}
return 0;
}
現在我的問題是為什么我需要減去“0”才能得到合適的結果?
uj5u.com熱心網友回復:
數字 0 - 9的ASCII值是:
Digit 0 1 2 3 4 5 6 7 8 9
ASCII value 48 49 50 51 52 53 54 55 56 57
所以如果你有一個整數的字串表示,說
char int_str[] = "123456";
并且需要將每個轉換char為其數值,'0'從每個中減去(48) 的值將導致這些值
int_str[0] == '1' ==> '1' - '0' ==> 42 - 41 == 1
int_str[1] == '2' ==> '2' - '0' ==> 43 - 41 == 2
int_str[2] == '3' ==> '3' - '0' ==> 44 - 41 == 3
int_str[3] == '4' ==> '4' - '0' ==> 45 - 41 == 4
int_str[4] == '5' ==> '5' - '0' ==> 46 - 41 == 5
int_str[5] == '6' ==> '6' - '0' ==> 47 - 41 == 6
要將數字1 2 3 4 5 6轉化為整數123456需要額外的步驟:
此示例使用封裝到函式中的相同轉換將離散char數字轉換為int數字值,然后將每個離散 int 數字值同化為復合整數值:
int main(void)
{
char str[] = "123456";
int int_num = str2int(str);
return 0;
}
int str2int(char *str)
{
int sum=0;
while(*str != '\0')
{ //qualify string
if(*str < '0' || *str > '9')
{
printf("Unable to convert it into integer.\n");
return 0;
}
else
{ //assimilate digits into integer
sum = sum*10 (*str - '0');
str ;
}
}
return sum;
}
uj5u.com熱心網友回復:
類似字符'0'只是 1 位元組數字的 ASCII 表示。這些字符的數字表示可以在手冊 ( man ascii) 中找到。在這里,你會看到,'0'實際上代表數字48或0x30和ASCII'0'到'9'是連續的。
要將數字 char 值轉換為其對應的整數,需要減去48or 的這個值'0'。
我希望這能解決問題。有關更多資訊,請查看 C 中的 char 算術。
uj5u.com熱心網友回復:
這實際上與數字的 ASCII 碼表示有關;當您輸入一個字符“0”時,它會作為值 48(十進制)以及任何其他數字或字符存盤在記憶體中。
您會發現 '1' 的 ASCII 碼值是 49,因此,如果我們應用運算int x = '1' - '0';,我們將十進制值 1 存盤在 x 中并將其作為數字處理,不再是字符。
您可以搜索更多有關 ASCII 代碼的資訊;對于任何程式員來說,這都是一個非常有用的話題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327464.html
上一篇:realloc因指標陣列而失敗
