在C语言中实现Luhn算法遇问题:存在bug的代码
Hey there! Let's work through this Luhn algorithm issue for your CS50x 2018 pset1 "credit" task— I remember struggling with this exact part when I took the course, so I feel your pain. Let's break this down step by step.
Troubleshooting Your Luhn Algorithm Implementation
First, Let's Lock Down the Full Luhn Steps (to avoid misalignment)
You mentioned part of the algorithm, but let's recap the complete process to make sure we're on the same page:
- Start from the second-to-last digit of the card number (counting from the right, this is the "even position" if you start at 1 for the last digit)
- Multiply every other digit (those even positions from the right) by 2
- For any product that's 10 or higher, add the individual digits together (or just subtract 9— it's a shortcut that gives the same result, e.g., 14 → 1+4=5 or 14-9=5)
- Sum all these processed doubled digits
- Add that sum to the total of the remaining digits (the ones you didn't multiply by 2, the odd positions from the right)
- If the final total is a multiple of 10, the number passes the Luhn check; if not, it's invalid
Common Mistakes That Trip Up CS50x Students
Chances are your bug is one of these super common pitfalls:
- Position mix-up: If you're treating "even positions" as counting from the left instead of the right, that's a guaranteed error. Always start counting from the last digit (rightmost) when applying Luhn.
- Botching two-digit products: Forgetting to split numbers like 18 into 1+8 and instead adding 18 directly will throw off your sum drastically.
- Incorrect digit extraction: When working with the card number as a long long, make sure you're pulling digits from right to left using
temp % 10(to get the last digit) thentemp /= 10(to chop it off). Going left to right is way harder here. - Merging sums too early: Keep separate variables for the sum of doubled digits and the sum of original digits— mixing them up mid-loop leads to messy, hard-to-debug calculations.
Example Working Snippet (C, for CS50x)
Here's a clean, commented implementation you can compare against your code:
#include <stdio.h> #include <cs50.h> int main(void) { // Get the card number from user long long card_num = get_long_long("Enter credit card number: "); long long temp = card_num; int sum_doubled = 0; int sum_original = 0; bool double_next = false; // Start with false: last digit doesn't get doubled while (temp > 0) { int current_digit = temp % 10; if (double_next) { int doubled = current_digit * 2; // Handle two-digit products: add digits or subtract 9 sum_doubled += (doubled > 9) ? (doubled - 9) : doubled; } else { sum_original += current_digit; } // Flip the flag for the next digit (moving left) double_next = !double_next; // Chop off the last digit we just processed temp /= 10; } int total_sum = sum_doubled + sum_original; if (total_sum % 10 == 0) { // Note: You'll still need to add card issuer checks (Amex, Visa, MasterCard) here printf("VALID\n"); } else { printf("INVALID\n"); } return 0; }
Quick Debugging Tips
- Test with a known valid number: Try
4003600000000014(a valid Visa). Manually calculate the sum:- Doubled digits (right-to-left even positions): 12=2, 02=0, 02=0, 62=12→3, 02=0, 02=0, 4*2=8 → total 13
- Original digits: 4+0+0+0+0+0+3 → total 7
- Final sum 13+7=20, which is divisible by 10. If your code doesn't return VALID for this, you know exactly where to dig.
- Add print statements: Print
current_digit,sum_doubled, andsum_originalin each loop iteration. Compare the values to your manual calculation to spot where things go wrong.
内容的提问来源于stack exchange,提问作者PY98
相关产品推荐
相关产品推荐

