次のように、配列の位置 0 に 1 の列、位置 1 に 10 の列、位置 2 に 100 の列を持つ long long 整数を文字列配列に変換しようとしています。
入力: 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])
と、予想どおり、「6」ではなく「53」になります。誰が何が起こっているのか説明できますか?
確かに 52 と 53 は ASCII 値に対応しますが、どうすれば整数に変換できますか? これをインラインで行うことはできますか?
プログラムのこの部分で私が目指しているのは、10、1,000、100,000、10,000,000 の列のすべての数値を合計することです。基数 10 のクレジット カード番号の 1 桁おき。これは、Luhn 検証の試みの 1 つのステップです。
// 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]);