C#Luhn CheckDigit生成器 - 返回10而不是0 [英] C# Luhn CheckDigit generator - returns 10 instead of 0

查看:187
本文介绍了C#Luhn CheckDigit生成器 - 返回10而不是0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我一直在尝试用C#制作一个mod10校验位计算器。我找到了一个可行的片段,但是,如果校验位为10,我似乎无法告诉程序如何返回0。它适用于所有其他数字,除了那些返回10的数据。有人可以帮助吗我在哪里插入这个?



Hi all,

I''ve been trying to make a mod10 check digit calculator in C#. I''ve found a snippet that works, however, I cannot seem to find out how to tell the program to return 0 if the check digit is 10. It works for all other numbers except the ones that return 10. Can somebody please help me with where to insert this?

public static int GetMod10Digit(string data)
        {
            int sum = 0;
            bool odd = true;
            for (int i = data.Length - 1; i >= 0; i--)
            {
                if (odd == true)
                {
                    int tSum = Convert.ToInt32(data[i].ToString()) * 2;
                    if (tSum >= 10)
                    {
                        string tData = tSum.ToString();
                        tSum = Convert.ToInt32(tData[0].ToString()) + Convert.ToInt32(tData[1].ToString());
                    }
                    sum += tSum;
                }
                else
                    sum += Convert.ToInt32(data[i].ToString());
                odd = !odd;
            }
            return (((sum / 10) + 1) * 10) - sum;
        }

推荐答案

使用模数运算符:如果x == 10,x%10将返回0。
Use the Modulus operator: "x % 10" will return 0 if x == 10.


试试这个,



try this,

public static int GetMod10Digit(string data)
{

 int sumOfDigits = data.Where((e) => e >= '0' && e <= '9')
 .Reverse()
 .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
 .Sum((e) => e / 10 + e % 10);
 //// If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.
 return sumOfDigits % 10;
}


这篇关于C#Luhn CheckDigit生成器 - 返回10而不是0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆