Maths is wrong: always result of 0

心不动则不痛 提交于 2021-02-05 12:33:33

问题


So I have some code which basically reads:

int foo = bar * (percentage / 100);

Where foo represents the percentage of bar. So, if bar was 100 and percentage was 20, we would expect 20/100 = 0.2 so 100 * 0.2 = 20... but that's not what happens. Every time, without fail foo = 0. I figured 'maybe it's not a whole number' so I tried:

float foo = bar * (percentage / 100);

foo still = 0. Any help would be appreciated, as I've never been great at math, but I'm pretty sure I'm not wrong on this bit of it


回答1:


The expression (percentage / 100) is of type integer and as such will be 0 whenever the result rounds to 0.

If you change one of the numbers in the expression to a type that handles decimals. The expression will evaluate to that type instead.

(percentage / 100.0)

and then when you multiply it with bar that expression will also be of the same type rather than int.

Alternatively you can change the order of execution

int foo = (bar * percentage) / 100;

There will be some loss of precision but you shouldn't get 0 unless bar * percentage is less than 100 as well.




回答2:


Change it to a decimal float foo = bar * (percentage / 100.0);




回答3:


The problem here is integer division. You need to do:

int foo = bar * (percentage / 100.0);

This tells the compiler you want a double or float back, not an int that will be 0 or 1.




回答4:


I think the issue in (percentage / 100). It's Integer, So 20/100 = 0. The source should: var foo = bar * (percentage / 100.0);

I hope this is helpful




回答5:


Try this:

float foo = (float)bar * ((float)percentage / 100.0);

To round up, do this:

in foo = (int)Math.Ceiling((float)bar * ((float)percentage / 100.0));


来源:https://stackoverflow.com/questions/22085579/maths-is-wrong-always-result-of-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!