Finding remainder, sometimes returns negative

My function often works, but sometimes it displays a negative number when I try to print the remainder.

Here is the function being defined:

1
2
3
4
5
6
7
8
9
10
11
  double remainder(double num1, double num2){
  
   int i;
   i = (num1/num2);
   double rem = num1 - (i * num2); /*Since an (int) truncates anything past the decimal,  */
                                   /*if we take the quotient in (int) form and multiply   */
                                   /*it by the decimal, then subtract from the numerator, */
                                   /*that will give us our remainder.                     */
                                   
   return rem;     /*Returns the remainder*/
                                            }



Here is the function being called in main():

1
2
3
4
5
 double a, b, endValue;
 printf("Input two numbers to divide the second by the first and output the remainder (e.g. 20,15): ");
           scanf("%lf,%lf", &a, &b);
                 endValue = remainder(a, b);           
    printf("The remainder is: %f\n", endValue);


If I put in 20,15 then it returns 5.00000000, and that is correct. However, if I input 23,12 it will return -1.000000

What is going on?
Strange... it works fine for me here. I get 11.00000 for 23,12.

What's probably happening is 'i' is getting truncated to 2, not 1. Try doing a floor operation to ensure it gets rounded down:

 
i = floor(num1/num2);
Works fine with my compiler (Xcode) so not real sure to be honest.
I noticed that it works fine when I run it under Dev-C++. But even with the floor function, it gives me -1 when I run it under Cygwin.

http://i.imgur.com/T8QR9.gif
Strange, isn't it?
Topic archived. No new replies allowed.