tags:

views:

154

answers:

5

I am so confused with Modulus in C. I am writing a small script that allows the user to input their two number vars, then they can either add, subtract, multiply, divide (easy) or modulus (haven't caught this one yet). What would I be doing wrong in this? I get the "invalid operands to binary %" error, which means I need to format it to an int since it is a float. However what is the best way of doing this with the following? Any C help would be greatly appreciated.

int main (void)
{
    float number1, number2, result;
    char symbol;

    //allow user interaction
    printf("Enter your formula: \n");
    scanf("%f %c %f", &number1, &symbol, &number2);



    switch (symbol) {
     case '%':
      result = number1 % number2;
      printf("Result: %f \n", result);
      break;
     default:
      printf("Operation Error. Program aborted. \n \n");
      break;
    }

    printf("Press any key to continue \n");

    getchar();
    return 0;
}

Where and how do I convert this?

A: 

Mod is an integer operation, so it cannot be used on floats. Your case should read something like:

result = (int)number1 % (int)number2;

which will convert both floats to integers, and perform the mod. However, note that you are losing precision by casting a floating point number to an integer, so it is likely the result may not be what you'd expect.

fbrereto
if i am not getting the right result with this method what would be the ideal method?
HollerTrain
You should be getting the right result. What do you get, and what do you expect instead?
Martin v. Löwis
What do you consider the 'right' result?
Henk Holterman
+1  A: 

I recommend to use the fmod function of the standard C library.

Martin v. Löwis
A: 

change

case '%':
     result = number1 % number2;

to

case '%':
    result = (int)number1 % (int)number2;

?

modulo division is for integers. Cast each operand to an integer.

Brian Schroth
+2  A: 

You can either use a statement like:

result = (int)number1 % (int)number2;

to cast your floats to ints and perform the modulus operation, but you'll lose the decimal precision.

You could also include math.h and use fmod

result = fmod(number1, number2);
Justin Niessner
A: 

The % operator only works on integer types. To perform the same task with floating points, you'd want to do something like:

#include <math.h>
float modulus(float a, float b)
{
   return a - b * floor(a / b);
}
mobrule