问题描述
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 的值是错误的。
解决方法
您不能对浮点变量使用模运算符。模和除法也不等价。
您可以使用 fmod
中的 math.h
函数:
#include <math.h>
h = std::fmod(60 * ((g-b) / diff) + 360,360);