c#数据类型和数组

本文关键字:数组 数据类型 | 更新日期: 2023-09-27 18:09:53

我正在为一些货币值创建一个数组。我将数组创建为整数,并意识到它需要是十进制值。当我将变量更改为小数并尝试运行它时,我得到"不能隐式地从小数转换为int"。悬停在变量上,它们看起来都是小数。我记得过去在整型数后面加上。00 m,以迫使它们变成小数,但这似乎没有什么区别。还有人明白吗?

    //Global var
    Decimal lastIndexUsed = -1;
    Decimal[,] quarters = new Decimal[10, 5];
    string[] Branch = new string[10];
       //Calc button
            decimal Q1;
            decimal Q2;
            decimal Q3;
            decimal Q4;
            Q1 = Decimal.Parse(txtQ1.Text);
            Q2 = Decimal.Parse(txtQ2.Text);
            Q3 = Decimal.Parse(txtQ3.Text);
            Q4 = Decimal.Parse(txtQ4.Text);
            lastIndexUsed = lastIndexUsed + 1;
            quarters[lastIndexUsed, 0] = Q1;
            quarters[lastIndexUsed, 1] = Q2;
            quarters[lastIndexUsed, 2] = Q3;
            quarters[lastIndexUsed, 3] = Q4;
            Branch[lastIndexUsed] = txtBranch.Text;

标记的部分是第一个出错的变量

            Decimal row;
            Decimal col;
            Decimal accum;
            //Calculate
            for (row = 0; row <= lastIndexUsed; row++)
            {
                accum = 0;
                for (col = 0; col <= 3; col++)
                {
               ***     accum = accum + quarters[row, col];***
                }
                quarters[row, 4] = accum;

c#数据类型和数组

lastIndexUsed用作数组索引,并且应该保持整数。

Decimal[,] quarters = new Decimal[10, 5];

索引号为整数。你不能用小数来索引。数组包含小数

我把它改成这样让它运行,它打印10.15,就像你期望的那样

`//Global var
    int lastIndexUsed = -1;
    Decimal[,] quarters = new Decimal[10, 5];
    string[] Branch = new string[10];
   //Calc button
        decimal Q1;
        decimal Q2;
        decimal Q3;
        decimal Q4;
        Q1 = Decimal.Parse("10.15");
        Q2 = Decimal.Parse("13");
        Q3 = Decimal.Parse("123.9877");
        Q4 = Decimal.Parse("321");
        lastIndexUsed = lastIndexUsed + 1;
        quarters[lastIndexUsed, 0] = Q1;
        quarters[lastIndexUsed, 1] = Q2;
        quarters[lastIndexUsed, 2] = Q3;
        quarters[lastIndexUsed, 3] = Q4;
        Branch[lastIndexUsed] = "hello";
        Console.WriteLine(quarters[0,0]);`

即使您使用的是小数数组,索引器仍然是整数。

Decimal lastIndexUsed;

应为

int lastIndexUsed