每行打印4件

时间:2016-12-23 05:26:10

标签: c loops

我有一些价值观,我希望每行打印4个项目!

for (i=0;<i<18;i++)
    number[i]=(2*i)+5;
for (i=0;i<18;i++)
    printf ("[%d]", number[i]; /* Gives me the full numbers consecutively */

我应该使用计数器来开始计算元素吗?当计数器变为3改变线,或者是否有更优雅的方式?

2 个答案:

答案 0 :(得分:3)

#include <stddef.h>
#include <stdio.h>

static int print_number_by_group(int *number, size_t size, size_t group) {
  if (number == NULL || group == 0) {
    return 1;
  }

  if (size == 1) {
    printf("[%d]\n", number[0]);
  }
  else if (size != 0) {
    printf("[%d]", number[0]);

    for (size_t i = 1; i < size; i++) {
      if (i % group == 0)
        printf("\n");
      printf("[%d]", number[i]);
    }
    if (size % group != 0) {
      printf("\n");
    }
  }
  return 0;
}

int main(void) {
  int number[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};

  print_number_by_group(number, sizeof number / sizeof *number, 4);
}

不要在家里试试,这只是为了好玩:

#include <stddef.h>
#include <stdio.h>

static int print_number_by_group(FILE *stream, int *number, size_t size,
                                 size_t group) {
  if (number == NULL || group == 0) {
    return 1;
  }

  size_t i = 0;
  size_t j = 1;
loop : {
  int num = number[i];
  if (j == group) {
    if (fprintf(stream, "[%d]\n", num) < 0) {
      return 1;
    }
    if (++i >= size) {
      return 0;
    }
    j = 1;
  } else {
    if (++i >= size) {
      if (fprintf(stream, "[%d]\n", num) < 0) {
        return 1;
      }
      return 0;
    } else {
      if (fprintf(stream, "[%d]", num) < 0) {
        return 1;
      }
    }
    j++;
  }
}
  goto loop;
}

int main(void) {
  int number[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};

  print_number_by_group(stdout, number, sizeof number / sizeof *number, 3);
}

答案 1 :(得分:0)

这不是火箭科学,但可以通过几行代码在一个循环中完成。

    function removeDollar($x) {
       $charactersToBeRemoved = array("R", "$", " ");
       $changedValue = str_replace($charactersToBeRemoved, "", $x);
       return $changedValue;
    }

   $money = "R$100,00";
   $newValue = removeDollar($money);
   echo $newValue;
   // output 100,00