Frage

I am trying to design the Denmark flag in C through PPM but I can't seem to get my function to work as well as I want to find a more efficient way to loop all the places together, instead of doing all if/else if statements.

 for(i=0; i < height; i++){
  for(x=0; x < width; x++){
    if(x <= width *.3 && i <= height * .3)
   {
     printf("%i", Pixel(255,51,51));
   }
    else if(x<= width * .1 && i <= height *.1)
   {
     printf("%i",Pixel(0,0,0));
   }
    else if(x <= width * .405 && i <= height *.3)
   {
     printf("%i", Pixel(255,51,51));
   }
    else if(x <= width * .4 && i <= height)
   {
     printf("%i", Pixel(0,0,0));
   }
    else
   {
     printf("%i", Pixel(255,51,51));
   }
 }
}

This is my body, which I have no idea how to loop together instead of creating mass amounts of if/else statements which half the time probably wont work....

void Pixel(int red, int green, int blue){
  printf("%i %i %i", red, green, blue);
}

Also for some reason my function will compile... Can anyone help me with this issue as well?

War es hilfreich?

Lösung

Read up on how to use logical operators && and ||.

There is no need to add separate checks for 'left red, middle white, right red', you can assume you are drawing in red and only check for the middle part.

Since you want to draw in White when [x > 0.3 && x <= 0.4] or [y > 0.3 && y <= 0.4], you can concatenate this into a single if check. The same goes for the black border -- it only needs a single check.

if (x < width * .1 || y < height * .1 || x > width * .9 || y > height * .9)
  ..black..
else
  if ((x > width *.3 && x <= width * .4) || (y > height *.3 && y <= height * .4))
    ..white..
  else
    ..red..

Also: Your Pixel routine already prints the RGB value, so there is no need to try that again when you call it. What happens now is that

printf("%i", Pixel(255,51,51));

first prints the R,G,B values and then attempts to print the 'result' of calling the Pixel function. This fails because Pixel does not return a value. Your compiler should have warned you about that, so please check your compile settings. (But note that adding a return x statement in that function does not help a bit, because it calculates nothing you are interested in.)

Finally, I'd strongly recommed using y instead of i to iterate a clearly-Y value. I noticed I used that 'instinctively' in my explanation.

After fixing a few smaller issues (for instance, Pixel outputs three digits separated by a space, but if you call it a second time, the first new digit will stick to the previous one) I got this:

flag of Denmark

in PPM format, which I could open correctly in Photoshop (and then convert to PNG because SO does not like PPM images).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top