2014-11-05 19 views
0
1 
    232 
    34543 
4567654 
567898765 

我正在尝试编写一个用于开发上述数字模式的c程序。 这是我写的开发相同的代码,但它失败,显示错误的答案未能使用c打印复杂数字模式

main() 
    { 
      int n, c, d, num = 1, space; 

      scanf("%d",&n); 

      space = n - 1; 

      for (d = 1 ; d <= n ; d++) 
      { 
       num = d; 

       for (c = 1 ; c < space ; c++) 
        printf(" "); 

       space--; 

       for (d = 1 ; c <= d ; c++) 
       { 
        printf("%d", num); 
        num++; 
       } 
       num--; 

       for (c = 1 ; c <= d ; c++) 
       { 
        printf("%d", num); 
        num--; 
       } 
       printf("\n"); 

      } 

      return 0; 
    } 

是我的代码有任何错误?有谁能够帮助我?

由于事先

回答

0

第一件事首先,您的环路使用d作为控制变量,而第二内部循环重新将其设置到1

for (d = 1 ; d <= n ; d++) 
    : 
    for (d = 1 ; c <= d ; c++) 

内环应使用c而不是d。一旦你解决这个问题,你得到的东西有点接近:

11 
    2332 
345543 
45677654 
5678998765 

你可以看到,中间数字正在打印太多次,你可以修复,通过调节第三内环开始一个值(记住三个内循环是前导空格,计数,并计数减少):

num--;      // one value lower 
for (c = 1 ; c < d ; c++) // one less time (< instead of <=) 

随着变化,你终于有所有的数字正确,但间距只需要一点工作:

1 
    232 
34543 
4567654 
567898765 

这就是调整第一内环的一个简单的事情:

for (c = 0 ; c < space ; c++) // start at zero rather than one 

随着所有这些变化(以及临时改变为使用恒定5而不是用户输入),我们最终了:

#include <stdio.h> 

int main (void) { 
    int n, c, d, num = 1, space; 

    n = 5; // scanf ("%d",&n); 

    space = n - 1; 

    for (d = 1; d <= n; d++) { 
     num = d; 

     for (c = 0; c < space; c++) 
      printf (" "); 

     space--; 

     for (c = 1; c <= d; c++) { 
      printf ("%d", num); 
      num++; 
     } 
     num--; 

     num--; 
     for (c = 1; c < d; c++) { 
      printf ("%d", num); 
      num--; 
     } 
     printf ("\n"); 

    } 

    return 0; 
} 

我们结束:

1 
    232 
    34543 
4567654 
567898765 

根据需要。


当然,也有这样做,如果你只是想在开始和结束每三个内部循环的条件更简洁的方式,如下证明:

#include <stdio.h> 

int main (void) { 
    int numLines; 

    numLines = 5; 

    for (int line = 1; line <= numLines; line++) { 
     // Spaces at start of line. 

     for (int spaces = 0; spaces < numLines - line; spaces++) 
      putchar (' '); 

     // Ascending digits. 

     for (int digit = line; digit < line * 2; digit++) 
      printf ("%d", digit); 

     // Descending digits and newline. 

     for (int digit = line * 2 - 2; digit >= line; digit--) 
      printf ("%d", digit); 

     putchar ('\n'); 
    } 

    return 0; 
}