我正在尝试将 long long 整数转换为字符串数组,其中 1 的列位于数组的位置 0,10 的列位于位置 1,100 的列位于位置 2,如下所示:
输入:4444555566667777 -----> 输出:[4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7]
为了测试我的代码,我写了最后一行printf("%d\n",number_str[3])
。我希望我的程序输出位置 4 的值“7”。相反,它输出“52”。正如我所料,将我的最后一行更改为printf("%d\n",number_str[4])
“53”而不是“6”。谁能解释发生了什么?
当然 52 和 53 对应于 ASCII 值,但是,我怎样才能将它们转换为整数呢?我可以排队吗?
在我的程序的这一部分中,我的目标是将 10、1,000、100,000、10,000,000... 列中的所有数字相加。以 10 为基数的信用卡号中的每隔一个数字。这是我尝试进行 Luhn 验证的一步。
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Program
int main(void)
{
// Get CC number
printf("Enter your credit card number: ");
long long number_ll = GetLongLong();
// printf("%lld\n", number_ll);
// Convert long long to string
char number_str[64];
sprintf(number_str, "%lld", number_ll);
// printf("%s\n", number_str);
// Get length of card number string
int cclength = strlen(number_str);
// Check the length of card number string
if ( ! (cclength == 13 || cclength == 15 || cclength == 16))
printf("INVALID\n");
else
printf("%d\n",number_str[3]);