Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

double

I have to use '%' with double numbers, but in C++ it doesn't 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 converted it, I will lose the fractional part, and I don't want.

Is there another alternative?

like image 344
Romulus Avatar asked Nov 27 '13 08:11

Romulus


2 Answers

% is not defined for doubles, but you can use fmod instead:

Compute remainder of division Returns the floating-point remainder of numer/denom (rounded towards 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;
}
like image 89
Nemanja Boric Avatar answered Oct 20 '22 19:10

Nemanja Boric


Use the fmod function

#include <math.h>

double x;
temp = fmod(x, 10.0);
like image 35
john Avatar answered Oct 20 '22 18:10

john