TQC+ C# 認證教學手冊

408、信用卡號檢查

☐易 ☑中 ☐難

參考程式碼

using System;

namespace CSD04
{
    class Program
    {
        static void Main(string[] args)
        {
            string card1 = "5181271099000012";
            string card2 = "5181271099000017";

            Console.WriteLine("Card Number: {0} total {1} is {2}", card1, total(card1), check(card1) ? "Valid" : "Invalid");
            Console.WriteLine("Card Number: {0} total {1} is {2}", card2, total(card2), check(card2) ? "Valid" : "Invalid");

            Console.ReadLine();
        }

        static int total(string card)
        {
            int total = 0;

            for (int i = 0; i < card.Length; i++)
            {
                int num = int.Parse(card.Substring(i, 1));

                if (i % 2 == 0)
                {
                    num *= 2;
                }

                total += (num % 10 + num / 10);
            }

            return total;
        }

        static bool check(string card)
        {
            if (card.Length != 16)
            {
                Console.WriteLine("信用卡必須為十六碼");
                return false;
            }

            return total(card) % 10 == 0;
        }
    }
}

參考程式碼 v2

Program.cs

using System;

namespace CSD04
{
    class Program
    {
        static void Main(string[] args)
        {
            string card1 = "5181271099000012";
            string card2 = "5181271099000017";

            check(card1);
            check(card2);

            Console.ReadLine();
        }

        static void check(string card)
        {
            int total = 0;

            for (int i = 0; i < card.Length; i++)
            {
                int n = int.Parse(card.Substring(i, 1));

                if (i % 2 == 0)
                {
                    n *= 2;
                }

                total += (n / 10 + n % 10);
            }

            Console.WriteLine("Card Number: {0} total {1} is {2}",
                card, total, total % 10 == 0 ? "Valid" : "Invalid");
        }
    }
}