【问题标题】:Formatted output in C based on end condition基于结束条件的 C 格式输出
【发布时间】:2021-03-16 14:42:57
【问题描述】:

我正在迭代 C 中的一些计数器,以将结果打印在像 012, 013, 014, etc... 这样分隔的单行上

我的代码因某些情况而终止,并且正在被机器人纠正。

如何在我的代码的最后一个值之后停止打印, 。 想法是获得一个只有唯一数字且按升序排列的 3 位数字 以789结尾;

我的功能如下:

void my_print_comb(void){
   for(int i = 47; i++ < 57 ; ){
      for(int j = 48; j++ < 57 ; ){
         for(int k = 49; k++ < 57 ; ){
             if( i != j && i != k && j != k){
                while( i < j && j < k){
                char a = i, b = j, c = k;
                my_putchar(a);
                my_putchar(b);
                my_putchar(c);
                my_putchar(',');
                my_putchar(' ');
                break;
                }
             }
         }
      }
   }
}

【问题讨论】:

  • 通过修改代码不在代码最后一个值之后打印, 。你介意发Minimal, Reproducible Example吗?
  • 也许,不要打印第一个数字的逗号。然后在数字前打印一个逗号。
  • 我通常选择的选项是在除第一个标记之外的每个标记之前打印分隔符。
  • 在除第一个项目之外的每个项目之前打印一个逗号,即使您事先不知道要打印多少项目。
  • for(int i = 47; i++ &lt; 57 ; ){ 这通常不是如何编写for 循环。 for (int i = 48; i &lt;= 57; i++) { 是首选,因为它更清楚它到底做了什么。

标签: c loops iteration output stdout


【解决方案1】:

打印不带逗号的元素之一。要么打印第一个,然后遍历数组的其余部分,打印每个元素前面有一个, ;或打印除最后一个元素之外的所有元素,每个元素后带有, ,然后打印最后一个元素。我更喜欢第一种方法。

由于您没有显示任何代码,我只是举个例子。

void pretty_print_ints(const int *array, size_t count)
{
    // Nothing to do.
    if (count == 0 || array == NULL) return;

    // Print the first element, without a `,` after it.
    printf("%d", array[0]);

    // If there are more elements in the list, print them all, but add a `, ` separator.
    for (size_t i = 1; i < count; i++) printf(", %d", array[i]);

    // Add a new line at the end.
    printf("\n");
}

如果我们不知道要打印多少元素,它也可以工作。例如,我们可以在遇到等于0 的元素时停止,而不是在打印count 元素时停止,我们唯一需要更改的是停止条件。如果我们反过来(用printf("%d, ", array[i]); 打印count - 1 元素,我们将无法处理这种情况)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2017-01-20
    相关资源
    最近更新 更多