0

I'm not getting the expected result when I do division. Can someone please tell me what I'm doing wrong?

int page_list_size = 20; 
int page_fault_counter = 0;
double failure = 0.0;
double success = 0.0;
failure = page_list_size / page_fault_counter;
success = 1 - failure;
printf("failure Is %lf\n",failure);
printf("success Is %lf\n",success);

failure Is 1.000000
success Is 0.000000

Should be some decimal number between 0 and 1, and they should add up to 1.

rockstar797
  • 137
  • 1
  • 2
  • 11

1 Answers1

2

You are not allowed to divide by 0. If the denominator is not 0, dividing ints results in an int, so you need to use floats or doubles to get a number between 0 and 1.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • The `page_fault_counter` counter gets incremented several times as I run my program. I was just trying to show what my declarations look like. – rockstar797 Dec 14 '15 at 02:03
  • The second sentence explains why you won't get a float when you divide ints – Lou Franco Dec 14 '15 at 02:05
  • Can you please elaborate? – rockstar797 Dec 14 '15 at 02:07
  • 1
    If your division uses two `int`s then the resulting decimal will be rounded down the nearest `int`. A decimal number between 0 and 1 will therefore always be 0 if you do the division with `int`s. Check the duplicate answer for more info. – Samidamaru Dec 14 '15 at 09:15