该代码旨在使用
Luhns算法验证信用卡号。它是EDX CS50课程的一部分,但是我决定在没有其自定义库的情况下尝试它,以尽可能地学习。我遇到的问题是,如果我运行下面的代码,那么答案就会出现错误(即,附加到整数输出的“ 9”)。现在,如果我要么取消按要求int random_integer = 0;
char random_character = 'M';
,则输出完全按预期工作。
wrong输出(留下那些随机变量评论):209
纠正输出(将其中一个(或两者)删除这些随机变量):20
char sum_to_str[3];
,问题就完全消失了。请让我知道您的想法,因为我更新了C,并且对理解细微差别很感兴趣。
char sum_to_str[10];
我尝试了以下内容:COMPONT/UNCOMENT the the the theRepopperting
添加
#include <stdio.h> // For Standard Input/Output
#include <stdlib.h> // For the atoi() function
#include <string.h> // For the strchr() and strlen() functions
// This value is the length plus one
#define MAX_INPUT_LENGTH 255
int main(void) {
char user_input[MAX_INPUT_LENGTH];
char *p;
// Output CLI instructions
printf("Welcome to the Credit Card Validator!!\n");
printf("INSTRUCTIONS: At the prompt, please provide a CC number.\n");
printf("NOTES ON LENGTH: Visa -> 13 || 16, AmEx -> 15 and MC -> 16\n");
// Algorithm
char example_card_num[] = "4003600000000014";
// Check the length
int card_num_length = strlen(example_card_num);
int skip_flag = 0;
int sum_of_values = 0;
char value_at_index;
char str_of_evens[20];
for (int i = card_num_length - 1; i >= 0; i--) {
char sum_to_str[3];
switch (skip_flag) {
case 0:
// Add 'odd' values together
value_at_index = example_card_num[i];
sum_of_values = sum_of_values + atoi(&value_at_index);
// Toggle flag
skip_flag = 1;
break;
case 1:
// Add 'even' values together (with multiplier)
value_at_index = example_card_num[i];
// 1. Convert each str to int
// 2. Multiply by two
// 3. Convert back to str in new variable
sprintf(sum_to_str, "%d", (atoi(&value_at_index) *2));
// Concatenate each substring to a new string
strcat(str_of_evens, sum_to_str);
// Toggle flag
skip_flag = 0;
break;
}
}
// int random_integer = 0;
// char random_character = 'M';
char value_at_index_two;
for (int i = 0; i < strlen(str_of_evens); i++) {
value_at_index_two = str_of_evens[i];
sum_of_values = sum_of_values + atoi(&value_at_index_two);
}
printf("~~~~~~~~~~~\n");
printf("Sum of Values 01: %d\n", sum_of_values);
// Terminate the program
return 0;
}
改造了
int random_integer = 0;
至
char random_character = 'M';
char sum_to_str[3];
char sum_to_str[3];
但value_at_index尚未初始化。因此,上述呼叫
example_card_num[]