I am writing a program that validates a credit card number based on length and Luhn's Algorithm. You can read the assignment here.
My problem here lies on the first part of the for loop where the odd numbers from the credit card number are multiplied by 2 and added to a (long integer) variable called total.
The problem here is that when I add the numbers to the long variable it comes out wrong. The total should be 20 or 2 + 0 + 0 + 0 + 0 + 12 + 0 + 8. Starting from the second to last number of course.
Counting starting from second to last number is that same as all even numbers if the length of number is odd and all odd numbers if length of number is even which is what I did.
Here is my code:
#include <cs50.h> #include <stdio.h> long get_long_len(long value); int get_digit_with_index(int index, long value); int main(void) { long card_num; long len; do { card_num = get_long("Number: "); len = get_long_len(card_num); } while (len < 13 || (len > 13 && len != 15 && (len != 16))); int total = 0; int total2 = 0; for (int i = 0; i < len; i++) { if (len % 2 == 0) { if (i % 2 != 0) { total += get_digit_with_index(i, card_num) * 2; } else if (i % 2 == 0) { total2 += get_digit_with_index(i, card_num); } } if (len % 2 != 0) { if (i % 2 == 0 || i == 2) { total += get_digit_with_index(i, card_num) * 2; } else { total += get_digit_with_index(i, card_num); } } } } long get_long_len(long value) { int l = 1; while (value > 9) { l++; value /= 10; } return l; } int get_digit_with_index(int index, long value) { int l = 0; index = get_long_len(value) - index; while (index > l) { l++; value /= 10; } return value % 10; }
https://stackoverflow.com/questions/66837938/need-help-adding-long-integer-long-to-long-integer-variable-in-c-through-for-l March 28, 2021 at 10:41AM
没有评论:
发表评论