Very close, but that code produces the 'inverse' of a color (effectively converting RGB to CMY) not it's complement. An equal blend with the inverse always produces gray 127.5, not likely what you'd want.

If you'd rather work in RGB, here's an easy complement formula:

float R = red(original);

float G = green(original);

float B = blue(original);

float minRGB = min(R,min(G,B));

float maxRGB = max(R,max(G,B));

float minPlusMax = minRGB + maxRGB;

color complement = color(minPlusMax-R, minPlusMax-G, minPlusMax-B);

Reference: HSL lightness is (min+max)/2, by taking twice that and subtracting original values, you get original, complement, and their gray blend all with the same lightness.

Example: if original = <160,80,40>, then complement = <40,120,160> and 50% blend = <100,100,100>. You can easily verify that all three have L = 100.

This formula also works for grayscale colors (like pure black as complement of pure white), with the obvious exception that the L's won't be equal in that case. (since H is undefined, and S is zero, L is the only value present, so it HAS to be the value that varies: black L=0, white L=255, blended L=127.5)

BTW, note that these formulae only produce 'mathematical' complements, not 'perceptual' complements. On a screen, with typical gamma issues, the RGB value that
*looks* like the halfway gray between 0 and 255 is really about 188 (not 127). (and none of these colorspaces - RGB, HSB, HSL - are any good for perceptual calcs)