为什么我使用此代码得到 0.0?

Why am I getting 0.0 with this code?

当我在 Windows 计算器实用程序中输入“15036/18218*100=”时,它 returns 82.53375782193435

我真正想要的是 17.47 (100 - 82.53),但目前这不是重点。

使用此代码:

// Example: thisQty == 3182; totalQty == 18218
private string GetPercentage(int thisQty, int totalQty)
{
    int diff = totalQty - thisQty; // this equates to 15036
    double prcntg = (diff/totalQty)*100; // this equates to 0.0 for some reason
    return string.Format("{0}%", prcntg);
}

...我得到 0.0 的 prcntg 值。为什么? ISTM,这与我在计算器实用程序中手动执行的操作相同。为什么不是 return 82.53375782193435?

您使用的是整数值(不存储派系部分),因此将其转换为双精度,或使用双精度参数类型(我的建议)。您的操作 15036/18218 解析为 0.82 并存储为 0 的整数值...最终 0 * 100 无论如何都会解析为 0,这就是您得到结果的地方。

试试这个,

private string GetPercentage(double thisQty, double totalQty)
{
    double diff = totalQty - thisQty; // this equates to 15036
    double prcntg = (diff/totalQty) * 100.0; // this equates to 0.0 for some reason
    return string.Format("{0}%", prcntg);
}

这也有小数部分,您将得到结果。

即使正确的数学答案是分数,2 int 的除法也是 int

为了让它保留小数部分,您必须除以一个包含小数部分的类型的数字(如 doubledecimal):

Console.WriteLine(GetPercentage(3182, 18218));

private string GetPercentage(int thisQty, int totalQty)
{
   int diff = totalQty - thisQty; // this equates to 15036
   double prcntg = (diff / (double)totalQty) * 100;
   return string.Format("{0}%", prcntg);
}

顺便说一句 - 如果你转换为 double difftotalQty 并不重要 - 因为两者都会执行 / 操作返回一个 double - 这意味着保留小数部分

根据 Gilad Green 的回答,这是我最终得到的结果,它给出了我最终想要的值,并将该值四舍五入为整数:

private string GetPercentage(int thisQty, int totalQty)
{
    int diff = totalQty - thisQty;
    double prcntg = (diff / (double)totalQty) * 100;
    prcntg = 100 - prcntg;
    int roundedPercent = Convert.ToInt32(prcntg);
    return string.Format("{0}%", roundedPercent);
}