两个 int 的百分比?
我想要得到两个整数,一个除以另一个得到小数或百分比。 如何获得这两个整数的百分比或小数? (我不确定这是否正确......我可能还很远......) 例如:
int correct = 25;
int questionNum = 100;
float percent = correct/questionNum *100;
这就是我认为我可以做到的方式,但它不起作用...我想将小数(如果有的话)转换为 100 中的百分比,例如在本例中它是 %25。有什么想法吗?
这是正确的代码(感谢 Salvatore Previti!):(
float correct = 25;
float questionNum = 100;
float percent = (correct * 100.0f) / questionNum;
顺便说一句,我正在制作一个项目,使用它来进行测验检查程序,这就是为什么我需要百分比或小数)
I want to get two ints, one divided by the other to get a decimal or percentage.
How can I get a percentage or decimal of these two ints?
(I'm not sure if it is right.. I'm probably way off...)
for example:
int correct = 25;
int questionNum = 100;
float percent = correct/questionNum *100;
This is how I thought I could do it, but it didn't work... I want to make the decimal (if there is one) into a percent out of 100 for example in this case it is %25. any ideas anyone?
Here is the correct code (thanks to Salvatore Previti!):
float correct = 25;
float questionNum = 100;
float percent = (correct * 100.0f) / questionNum;
(btw, I am making a project using this for a quiz checking program that is why I need the percentage or decimal)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不添加
.0f
,它将被视为整数,并且整数除法确实与浮点除法有很大不同:)如果您需要其中的整数,您可以当然可以再次将
float
或double
转换为整数。如果您知道 n 值小于 21474836(即 (2 ^ 31 / 100)),则可以使用整数运算完成所有操作。
如果你得到 NaN 是因为无论你做什么,当然你都不能除以零......这是没有意义的。
If you don't add
.0f
it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)If you need an integer out of this you can of course cast the
float
or thedouble
again in integer.If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.
If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.
两个选项:
在乘法之后进行除法:
在除法之前将
int
转换为float
Two options:
Do the division after the multiplication:
Convert an
int
to afloat
before dividing其中之一必须是进入的浮点数。确保这一点的一种可能方法是:
否则,您将执行 整数除法,截断数字。另外,您应该使用
double
,除非有充分的理由使用float
。您将遇到的下一个问题是,某些百分比可能看起来像 24.9999999999999%,而不是 25%。这是由于浮点表示的精度损失造成的。你也必须决定如何处理这个问题。选项包括 DecimalFormat 来“修复”格式化或 BigDecimal 来表示精确值。
One of them has to be a float going in. One possible way of ensuring that is:
Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using
double
unless there's a good reason for thefloat
.The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.