两个int的百分比? [英] percentage of two int?

查看:296
本文介绍了两个int的百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得两个整数,一个除以另一个以获得小数或百分比。
如何获得这两个整数的百分比或小数?
(我不确定它是不是......我可能会离开...)例如

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;

这就是我认为我能做到的,但它没有用......我想要将十进制(如果有的话)变为100的百分比,例如在这种情况下它是%25。任何人的想法?

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?

这是正确的代码(感谢Salvatore Previti!):

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)

推荐答案

如果你不添加 .0f 它将被视为一个整数,并且整数除法与浮点除法确实有很大不同:)

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 :)

float percent = (n * 100.0f) / v;

如果你需要一个整数,你当然可以抛出浮点数 double 再次以整数形式显示。

If you need an integer out of this you can of course cast the float or the double again in integer.

int percent = (int)((n * 100.0f) / v);

如果您知道您的n值小于21474836(即(2 ^ 31/100)) ,你可以使用整数运算。

If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.

int percent = (n * 100) / v;

如果你得到NaN是因为你做了什么你当然不能分为零...它没有没关系。

If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.

这篇关于两个int的百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆