Search code examples
c++rgbhsvmodulo

Error in C++ Program for RGB to HSB conversion


I wrote the following code, which seems fine to me, but I'm getting a compilation error:

error: invalid operands of types 'double' and 'int' to binary 

My Code:

#include <iostream>
#include <cmath>
using namespace std;

class ColourChecking
{
private:
    double r, g, b;
public:
    void hsb(double a, double c, double d)
    {
        r = a/255.0; g = c/255.0; b = d/255.0;
        double cmax = max(r, max(g, b));
        double cmin = min(r, min(g, b));
        double diff = cmax - cmin;
        double h, s, b;
        // Hue Calculation
        if (cmax == cmin)
            h = 0;
        else if (cmax == r)
            h = (60 * ((g-b) / diff) + 360) % 360;
        else if (cmax == g)
            h = (60 * ((b-r) / diff) + 120) % 360;
        else if (cmax == b)
            h = (60 * ((r-g) / diff) + 240) % 360;

        // Saturation Calculation
        if (cmax == 0)
            s = 0;
        else
            s = (diff / cmax) * 100.0;

        // Brightness Calculation
        b = cmax * 100;

        cout << "Hue: " << h << endl;
        cout << "Saturation: " << s << endl;
        cout << "Brightness: " << b << endl;
    }

};

int main()
{
    ColourChecking Calculate;
//    Calculate.hsb(31, 52, 29);
    Calculate.hsb(45, 215, 0);
    return 0;
}

How do I resolve this error?

When I changed the "%" operator to "/" operator, values of saturation and brightness were correct, But value of h is wrong.


Solution

  • You cannot use the modulo operator on a floating point variable. Also modulo and division are not equivalent.

    You can use the fmod function from math.h :

    #include <math.h>
    h = std::fmod(60 * ((g-b) / diff) + 360, 360);