简体   繁体   中英

c# datatypes and arrays

I am creating an array for some monetary values. I created the array as an integer and realized it needs to be decimal values. When I change the variables to decimals and try and run it, I get "Cannot be implicitly converted from decimal to int." I hover over the variables and they all appear to be decimals. I remember in the past placing .00M after int's to force them to be a decimal, but this doesn't seem to make a difference. Does this make sense to anyone else?

    //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;

The marked part is the first of many variables which error.

            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;

lastIndexUsed用作数组索引,应保留为整数。

Even though you are using an array of decimals, the indexer is still an integer.

Decimal lastIndexUsed;

should be

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

The index numbers are integers. You can't index by decimals. The array contains decimals.

I changed it to this to get it to run and it prints 10.15 like you'd expect

`//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]);`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM