简体   繁体   English

C#背景工人divison

[英]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. ACon是一个个人类,它在其中的字典内容上调用保存功能。

   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. 我希望它能通过给出关键字/ /总密钥* 100来报告进度,但这不起作用。

No matter what type I use for pctg; 无论我用什么类型的pctg; short, int, float, double, num/Len always = 0, yet if I switch it around, Len/num gives the correct value. short,int,float,double, num / Len always = 0,但如果我将其切换, Len / num给出正确的值。 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) 以下是VS2010(专业版)的一些截图

pctg as double: pctg为double: pctg为double

pctg as float: pctg as float: pctg as float

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

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

Its not that you are changing the type for pctg, its based on the types of num and Len 它不是你要改变pctg的类型,它基于num和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. 如果numLen都是整数,那么你的代码将执行整数除法,之后它会将该整数转换为浮点数。

As mentioned by @CDspace below, the integer division will round to the nearest int, in your case, zero. 如下面的@CDspace所述,整数除法将舍入到最接近的int,在您的情况下为零。 Then casting zero to any other type is still zero. 然后将零转换为任何其他类型仍然为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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