C# 获取c中的数字#

C# 获取c中的数字#,c#,numbers,digits,C#,Numbers,Digits,我希望能够从C#中的数字中提取任意数字,因此我创建了一个函数来实现这一点。我只用数学来计算数字。这是我的密码 static int GetDigit(int number, int k) { // k is the positiong of the digit I want to get from the number // I want to divide integer number to 10....0 (number of 0s is k) and

我希望能够从C#中的数字中提取任意数字,因此我创建了一个函数来实现这一点。我只用数学来计算数字。这是我的密码

static int GetDigit(int number, int k)
    {
        // k is the positiong of the digit I want to get from the number
        // I want to divide integer number to 10....0 (number of 0s is k) and then % 10
        // to get the last digit of the new number
        return (number / (int)Math.Pow(10, k-1)) % 10;
    }

但是,有一条错误消息-“错误1无法将类型“double”隐式转换为“int”。存在显式转换(是否缺少转换?)。我认为Math.Pow返回double,所以它尝试将数字类型转换为double。非常感谢您的帮助:)

是否转换为整数

static int GetDigit(int number, int k)
    {
        // k is the positiong of the digit I want to get from the number
        // I want to divide integer number to 10....0 (number of 0s is k) and then % 10
        // to get the last digit of the new number
        return (int)(number / Math.Pow(10, k)) % 10;
    }
}

是,
Math.Pow
返回
double
。因此,您需要考虑如何将
double
转换为
int
。。。你试过什么?(你为什么把结果分配给
number
而不是仅仅返回它呢?)是的,它是这样工作的,即使我把(int)放在Math.Pow之前,它仍然工作。无论如何,谢谢:)现在的问题是,它返回的数字是从右向左的。例如GetDigit(521671,1),它将返回1。有什么想法吗?@leppie这是一个很好的观点,我一定是错加了。我本来打算做一次尝试,但后来决定不做了,结果就离开了。