-1

I am trying to get percentage but the result is error, i have expression as:

Uper=(Upcount/total)*100;

where Uper is float while Upcount and total is integer i am getting the result Uper=0.

Zsolt Botykai
  • 50,406
  • 14
  • 85
  • 110
Salman Raza
  • 1,635
  • 6
  • 18
  • 18

2 Answers2

3

An int divided by an int will result in an int. That could be 0. Multiply 0 * 100, convert to float, and the result is still 0.0. You need at least one of the operands to be floating point before the division will give a floating point result.

Try:

Uper = ((float)Upcount/(float)total)*100.0;

The extra (float) is me being paranoid that this line might be modified in the future without fully understanding the floating-point requirement. The 100.0 is to be explicit about what you want -- a floating point result.

Perhaps changing Upcount or total to float would make more sense.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • 1
    If at least one member of the mathematical operation is a Float/Double then the result will always be a Float/Doube. No need to pe paranoid and add 3 casts when you can do it with 1 cast only – Adel Boutros Jan 03 '12 at 11:17
  • There's only two casts. Yes, it's a bit noisy to read but in my experience code changes often over time, sometimes with brute-force search and replace mechanisms, and someone comes along later to fix compile errors without necessarily understanding the _reason_ for code to be written in a certain way. Write whatever makes the most sense for _you_ -- as I've written this code in the manner I think gives it the best chance of surviving maintenance programmers for a decade to come. – sarnold Jan 03 '12 at 11:21
  • You are right about everyone writing the way they like but in the problem we have here, it is not relating to a programming language, it is rather a basic concept of Computers because the division differs between integers and floating point values. So the automation part is not required but by the machine itself for computing purposes – Adel Boutros Jan 03 '12 at 13:54
2

the division of 2 integers will always result in an integer which is 0 in your case.

To solve this, use the following code:

Uper = ((Double) Upcount) / total * 100

Casting at least 1 member to Double or Float will get the result you want

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89