简体   繁体   中英

C# Background Worker divison

I am trying to use a background worker which for each key in a dictionary save the contents to file. ACon is a personal class that calls a save function on the contents of a dictionary within it.

   private void bwSaver_DoWork(object sender, DoWorkEventArgs e)
    {
        string[] Keys = ACon.GetKeys();
        int num = 0;

        foreach (string s in Keys)
        {
            ACon.Save(s);
            int Len = Keys.Length;
            double pctg = (num / Len);

            //Below was by first attempt at getting the percentage. Above are my debugging attempts.
            bwSaver.ReportProgress(num/Keys.Length*100);
            num++;
        }
    }

I was hoping for it to report the progress by giving the key it is on / total keys * 100 for percentage but this wasn't working.

No matter what type I use for pctg; short, int, float, double, num/Len always = 0, yet if I switch it around, Len/num gives the correct value. Adding or removing brackets doesn't change anything. Am I just being silly and missing something or am I coding something wrong?

Here is some screenshots from VS2010 (Professional)

pctg as double: pctg为double

pctg as float: pctg as float

pctg as double, without brackets: pctg为double,不带括号

pctg with Len and num swapped: pctg与Len和num交换

Its not that you are changing the type for pctg, its based on the types of num and Len

Try:

float pctg = ((float)num / (float)Len);

If both num and Len are ints, then your code would do integer division, after which it would cast that integer to a float.

As mentioned by @CDspace below, the integer division will round to the nearest int, in your case, zero. Then casting zero to any other type is still zero.

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