无法将类型'double'隐式转换为'long'

Ara*_*ash 14 c# double long-integer

在这段代码中,我在评论的行中得到了上述错误.

public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter < i.Length; counter++)
    {
        nums[counter] = Convert.ToInt32(i[counter]);
    }

    u = nums[0];
    int firstdigits = Convert.ToInt32(Math.Floor(Math.Log10(u) + 1));
    v = nums[1];
    int seconddigits = Convert.ToInt32(Math.Floor(Math.Log10(v) + 1));
    if (firstdigits >= seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;        
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

什么是问题?谢谢!

And*_*are 18

Math.Pow方法返回a double,而不是一个,long因此您需要更改代码以解决此问题:

x = (long)(u % Math.Pow(10, m));
Run Code Online (Sandbox Code Playgroud)

此代码将转换double结果Math.Pow并将该值赋值给x.请记住,您将失去所有提供的精度decimal(这是一个浮点类型,可以表示十进制值).转换为long将截断小数点后的所有内容.

  • 在铸造时不要忘记溢出,这将完全弄乱.示例:`(long)double.MaxValue == -9223372036854775808` (5认同)

Adr*_*der 5

变更类型

long x;
long y;
long w;
long z; 
Run Code Online (Sandbox Code Playgroud)

double x;
double y;
double w;
double z; 
Run Code Online (Sandbox Code Playgroud)

或者利用

Convert.ToInt64
Run Code Online (Sandbox Code Playgroud)


Ena*_*ane 5

Math.Pow返回一个double.

%的右侧(RHS)只能是整数类型.

你需要

x = u % (long)Math.Pow(10, m);///<----here
y = u / (long)Math.Pow(10, m);///here
w = v % (long)Math.Pow(10, m);///here
z = v / (long)Math.Pow(10, m);///here
Run Code Online (Sandbox Code Playgroud)

此外,您有可能将零除以并破坏宇宙.

  • 将模数运算的结果转换为"long"而不仅仅是"Math.Pow"的结果会更好.还要记住,如果编译器能够计算出`u`或`v`是浮点类型,那么你的代码仍然无法编译,因为表达式的结果仍然不能隐式转换为`long` .最好转换整个表达式的结果(正如我在答案中所示)以避免所有这些问题. (3认同)