Search code examples
javaconvertersrgbcmyk

RGB to CMYK converter in Java without imports


I've the task to write a very easy rgb to cmyk converter in java and my attempts aren't working. Looking up for solutions didn't help, since everyone uses libaries and imports I can't use here. I hope someone sees my mistake.

int w;
    int c;
    int m;
    int y;
    int k;

    if (r+b+g==0) {
        System.out.println("Ist alles 0");
    } else {
        int max =  Math.max(Math.max(r,b),g);
        w = (max / 255);

        r = r/255;
        g = g/255;
        b = b/255;

        c = ((w-r)/w);
        m = ((w-g)/w);
        y = ((w-b)/w);
        k = 1-w;
        System.out.println(c+" "+m+" "+y+" "+k);
    }

This is the part where I try to convert the r, g and b values (int) I get via user input to cmyk.

Edit: I know that there are post like these, but the solutions always include libaries and imports I'm NOT allowed to use.


Solution

  • The below code will store zero in r as the initial value of r is less than 255 and r is an int. So as per integer division r/255 will be zero.

    r = r/255;
    

    Instead you can store the result of division in a double variable, try the below (make sure at least one of the operand in the division is a double, else you can cast it to double)

    double rC = r/255.0;
    c = ((w-rC)/w);