Error C2296: '%': illegal, left operand is of type 'double' in C ++

I need to use '%' with double numbers, but in C ++ it does not work. Example:

double x; temp = x%10; 

I get this error:

 error C2296: '%' : illegal, left operand has type 'double' 

How can I solve this problem without converting the number from double to integer? If I convert it, I will lose the fractional part, and I do not want to.

Is there any other alternative?

+6
source share
2 answers

% not set for doubles, but you can use fmod :

Calculate remainder of division Returns the remainder with / denom floating point numbers (rounded to zero):

Example (adapted for C ++) from http://www.cplusplus.com/reference/cmath/fmod/ :

 #include <cmath> /* fmod */ #include <iostream> int main () { std::cout << "fmod of 5.3 / 2 is " << std::fmod (5.3, 2) << std::endl; return 0; } 
+14
source

Use the fmod function

 #include <math.h> double x; temp = fmod(x, 10.0); 
+3
source

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


All Articles