int print_pattern(){
int x;
int y;
int i;
//for loop for the bottom and the top, 0 is the top and 1 is the bottom while it stops at anything above 2.
for (i = 0; i<2;i++){
//loop to the current number
for (x=1;x<=input;x+=2){
// top or bottom, this is the top because i had made the top of the diamond the 0
// therefore this makes my diamond print the top of the function.
if ( i == 0){
//starts for the top of the diamond. and counts the spaces.
for (y=1; y<=input-x; y++){
printf(" ");
}
//starts the printing of the diamond.
for (y=1; y<2*x;y++){
printf("%d ", y);
}
}
//bottom of the diamond, which is from the 1. For this spot it take in the one from the for loop to
// this if statement.
if (i==1){
//counting spaces again
for(y = 1; y<=x; y++){
printf(" ");
}
//printing again but this is the bottom of the pyramid. #really need to comment more
for(y = 1; y<(input-x)*2;y++){
printf("%d ", y);
}
}
//next line starts when printing out the numbers in the output.
printf("\n");
}
}
}
输出应该看起来像每行以奇数结尾的数字菱形。但它会超过输入 +2 数字,然后也不会打印最后一行。哪个应该有一个。
1 1
1 2 3 1 2 3 4 5
1 2 3 4 5 1 2 3 4 5 6 7 8 9
1 2 3 1 2 3 4 5 6 7
1 1 2 3
左边是预期的,右边是我目前输入 5 时得到的结果。
最佳答案
因为你已经增加了x
通过上部的 2,您不需要让打印循环运行到 y<2*x
.它可能应该运行到 x
.
下部的打印循环受到 y<(input-x)*2
的影响。应该是 y<input-x*2
(你想每次少打印2)。
通常我会尝试以更通俗易懂的方式命名变量,例如 printStartPosition
, maxNumToPrint
, 像这样的东西。这使得理解程序变得更加容易。
作为增强,这两个代码块取决于 i
x
内的值循环在结构上非常相似。人们可以尝试利用它并将它们都折叠成一个函数,该函数获取一个 bool 参数,如“升序”,递增y
。为真时递减,为假时递减。这是否提高或阻碍了可读性将不得不被看到。
此外,如果可能,请将变量保留在本地。
关于c - 在 C 中打印数字钻石,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427594/