showing a percentage number for two variables in c#
本问题已经有最佳答案,请猛点这里访问。
我有两个变量,我想用百分比表示,当我用操作符计算它们时,结果是0,为什么?请帮帮我。谢谢这是我的资料来源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int count = (from a in dc.jawabans where a.q14 =="5 : Sangat Baik/ Sangat Puas" select a).Count(); TextBox1.Text = count.ToString(); int total = (from b in dc.jawabans where b.q14 !="" select b).Count(); TextBox2.Text = total.ToString(); int persen = (count / total) * 100; TextBox3.Text = persen.ToString(); |
这就是结果
1 | int persen = (int)((double)count / total * 100); |
这样写:
1 | decimal persen = (count / (decimal)total) * 100; |
之后,如果你愿意,你可以把它围起来:
1 | TextBox3.Text = Math.Round(persen, 2).ToString(); |
2个整数的除法是一个整数,因此应该指定其中一个是十进制。
1 | decimal persen = (count / (decimal)total) * 100; //count 20, total 100, so person will be 0 if it is int in your code |
如果你用int做除法,它会给你int而不是双倍。因此,根据您的要求,可以将计数或合计转换为十进制或double。
这是因为您要做的和是整数,所以值被四舍五入为最接近的整数-例如,如果
1 | int persen = (count / total) * 100; |
和做一样吗
1 2 | int persen = (count / total); //this = 0 as it would evaluate to 0.2 => 0 persen = persen * 100; //still 0 |
反之
1 2 | int persen = ((double)count / (double)total) * 100; //This would be 20, as count and total are both cast to a double - it also works if you only cast one of them |
因为你将两个整数分开,所以结果也是整数。您可以将count和total设置为double,然后得到正确的结果。