提问者:小点点

RGB到HSB转换的C++程序出错


我写了下面的代码,在我看来很好,但是我得到了一个编译错误:

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

我的代码:

#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;
}

如何解决此错误?

当我将“%”运算符更改为“/”运算符时,饱和度和亮度的值是正确的,但h的值是错误的。


共1个答案

匿名用户

不能对浮点变量使用模运算符。模和除也不等价。

您可以使用math.h中的fmod函数:

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

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(rgb|hsb|转换|c++|程序|出错)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?