How can I convert Float to Int with a module in C?

I am so confused with the module in C. I am writing a small script that allows the user to enter their two numbers-vars, then they can either add, subtract, multiply, divide (just) or the module (harbor "t caught it yet). What am I will I do it wrong? I get the error "invalid operands to binary%", which means that I need to format it to int, since this is a float. However, what is the best way to do 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 to do it?

0
source share
5 answers

You can use an instruction like:

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

to output your floats to int and perform a module operation, but you will lose decimal precision.

You can also include math.h and use fmod

 result = fmod(number1, number2); 
+3
source

I recommend using the fmod function of the fmod standard library.

+2
source

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

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

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

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

which converts both floats to integers and executes mod. However, note that you are losing precision by dropping the floating point number to an integer, so most likely the result may not be what you expected.

0
source

change

 case '%': result = number1 % number2; 

to

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

?

modulo division for integers. Pass each operand to an integer.

0
source

All Articles