Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the percentage that is one integer to another

Tags:

c

math

I have two integers (amount of bytes of two files). One is always smaller if not the same than the other. I want to calculate the percentage that the smaller is of the bigger.

I'm using plain C. I've applied the math formula, but am getting always 0:

printf("%d\r", (current/total)*100);

Any ideas?

like image 295
Luca Matteis Avatar asked Dec 07 '22 23:12

Luca Matteis


1 Answers

Try

printf("%g\r", (((double)current)/total)*100);

instead. Integer division always rounds towards zero. By converting one of the numbers to double first, you will trigger floating point division. If you would like to use integer arithmetic, you could also use

printf("%d\r", (100*current)/total);

which will print the percentage rounded down to the next integer.

like image 198
Sven Marnach Avatar answered Dec 29 '22 14:12

Sven Marnach