Find a percentage that is one integer for another

I have two integers (the number of bytes from two files). One is always smaller, if not the other. I want to calculate a percentage that is less than more.

I use plain C. I applied a math formula, but always get 0:

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

Any ideas?

+4
source share
5 answers

Try

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

instead of this. Integer division is always rounded to zero. Converting one of the numbers to double , first you start floating point division. If you want to use integer arithmetic, you can also use

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

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

+9
source

Sven will give you good advice.

If you want to keep integers, do the multiplication before division:

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

You will get a rounded result.

Integral division using numerator < denominator always gives 0. This explanation of your problem is "always 0". Multiplying by 100 before dividing gets an integral part of your division (in percent)

my2c

+3
source

I recommend scaling the nominee before performing the split:

 const float ratio = (100.f * current) / total; 

Here, creating 100 floating point literals will help the calculation, so there are no explicit tricks that are also an advantage.

+2
source

Better to try:

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

Since the answer will be in a floating point.

0
source

Integer division is rounded down, so if your answer is less than 1, you will get 0.

You can try something like this:

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

However, you always get an integer.

If you produce a numerator in a float, you will get a floating division and the correct answer.

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

However, you can trim the zeros after, for example, for three digits to a decimal and after you can use:

 printf("%3.2f\r", ((float)current/total * 100)); 

Departure:

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

0
source

Source: https://habr.com/ru/post/1338451/


All Articles