【问题标题】:CS50 Luhn's Algorithm in C. Help much appreciated :)CS50 Luhn's Algorithm in C. 非常感谢帮助:)
【发布时间】:2020-12-12 20:22:39
【问题描述】:

我需要使用 Luhn 的算法和我们目前在 CS50 中学到的知识(没有数组)来解决下面链接上的问题。

我的程序可以编译,但无法识别卡类型。我做错了什么?

提前非常感谢!

问题:https://cs50.harvard.edu/x/2020/psets/1/credit/#:~:text=check50%20cs50/problems/2020/x/credit

/* This program checks if a bank card number is syntactically valid, using Luhn's algorithm */

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{
    long long n, temp;
    int digit, last, first, product;
    int lenght = 0;
    int sumOdd, sumEven;


// Prompt user for input as long as the inputted number is equal or smaller than zero

do
 {
    n = get_long_long("Enter your credit card number without special characters:\n");

 } while (n < 0);


// Count the number of digits

while (n > 0)
 {
     n = n/10;
     lenght++;
 }

// Check if the number's length is valid

if (lenght != 13 && lenght != 15 && lenght != 16)
{
    printf("INVALID");
}

// Find the last digit and add it to the even sum

while (n > 0)
{
    last = n % 10;
    temp = n - last;
    sumEven = sumEven + last;

}

/* Starting with second-to-last digit, multiply every other digit by 2. Add those
products together and then add the sum to the sum of the digits that weren't multiplied by 2 */

while (n > 0)

{
    digit = n % 10;
    temp = n/10;

    if (lenght % 2 == 0)
    {
        product = digit * 2;
        sumOdd = sumOdd + product;

    } else

    {
         sumEven = sumEven + digit;

    }

// If the last digit of the sum of sums is zero print the number. Else print INVALID.

    if (sumOdd + sumEven % 10 != 0)
    {
        printf("INVALID\n");

    }
    else
    {
        printf("%lld\n", n);
    }

// Identify the user's card type as per CS50 Credit instructions. Cards commencing with 3 are AMEX, with 5 MasterCard and with 4, VISA.

while (first >= 10)
{
    first = n;
    first = first / 10;

    if (first == 3)
    {
        printf("AMEX\n");
    }

    if (first == 5)
    {
        printf("MASTERCARD\n");
    }

    if (first == 1)
    {
        printf ("VISA\n");
    }

}

}

}

【问题讨论】:

  • 修复您的代码格式。正确的支撑和缩进应该是您做的第一件事,而不是最后一件事。
  • 你把 n 完全分开了,好几次。您不应该先将第一个数字保存在某个地方吗?还是从原始数字重置 n?

标签: c cs50


【解决方案1】:

你有几个连续的 while 块

while (n>0){
   // some code  
}

while (n>0){
   // some code  
}

您的程序只会在 n 不再大于 0 时退出第一个循环。当它到达下一个 while 循环时,n 仍然不会大于 0,因此永远不会进入下一个 while 循环的主体。您的大部分代码没有被执行。

【讨论】:

  • 嗨@BigBill!你说的太对了。马上去修。还有什么问题吗?非常感谢您的反馈!希望你有一个好的周末! :)
猜你喜欢
  • 1970-01-01
  • 2018-10-11
  • 2014-07-27
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多