【问题标题】:Why is my image not matching what I expect it to look like?为什么我的图像与我期望的不匹配?
【发布时间】:2013-10-29 07:44:09
【问题描述】:

所以,我必须创建一个 ppm 文件,它会给我意大利国旗的图像(3 个垂直条,从左到右依次为绿色、白色和红色)。并且图像必须是 600 x 400。(按行列)我尝试多次重写我的代码,但是,我的图像只是水平放置而不是垂直放置的三个条。此外,线条并不完全平整。但最大的问题是,为什么我的绿色、白色和红色条不垂直?非常感谢任何帮助。

这是我的代码:

#include <stdio.h>

int main() {
   printf("P6\n");
   printf("%d %d\n", 600, 400);
   printf("255\n");

   int height, widthGreen, widthWhite, widthRed, i, j;
   unsigned char Rcolor, Bcolor, Gcolor;

   widthGreen = 200;
   widthWhite = 400;
   widthRed = 600;
   height = 400;

   for (j = 0; j < height; j++) {
      for (i = 0; i < widthGreen; i++) {
         Rcolor = 0;
         Gcolor = 128;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 0; j < height; j++) {
      for (i = 201; i <= widthWhite; i++) {
         Rcolor = 255;
         Gcolor = 255;
         Bcolor = 255;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 0; j < height; j++) {
      for (i = 401; i <= widthRed; i++) {
         Rcolor = 255;
         Gcolor = 0;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   return (0);
}

【问题讨论】:

标签: c image ppm


【解决方案1】:

四件事:第一是在值之间添加空格。第二种是在每行之后添加换行符。第三个是将值打印为(无符号)整数,而不是字符,255128 都不会打印为有效字符。第四种是使用 one 循环作为高度,其中三个循环用于颜色。把循环计数器想象成像素,你就会明白为什么了。

【讨论】:

    【解决方案2】:

    你为什么使用 printf ?您应该使用 i 和 j 索引来构建数组并将其索引到数组中。在您的代码中,i 和 j 变量仅用作循环计数器,而不是坐标。

    你在做什么:

    for each line
         print some green
    
    for each line
        print some white
    
    for each line
        print some red
    

    你应该做什么:

    for each line
        print some green
        print some white
        print some red
    

    您还可以使用更有意义的变量名称,例如 row 代替 j 和 col(用于列)代替 i

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多