使用自定义的行,列和长度打印重复的菱形形状

时间:2019-10-18 06:44:30

标签: c printf

我是C语言的新手,我正在尝试根据从输入的菱形输入的行(2〜10),列(2〜10)和长度(3、5、7、9)打印菱形用户。

使用下面的代码,我可以正确打印钻石和钻石的数量,但是我无法正确地获得它们之间的距离。

void printDiamondWith(int diamondlength, int numberOfDiamonds) {

    int i, j, k;
    int star, space;

    star = 1;
    space = diamondlength;

    for (i = 1; i < diamondlength * 2 - 1; i++) {
        for (k = 0; k < numberOfDiamonds; k++) {
            for (j = 0; j < space; j++) {
                printf(" "); // Print the distance for the previous star
            }
            for (j = 1; j < star * 2; j++) {
                printf("*");
            }
            for (j = 0; j < space; j++) {
                printf(" "); // Print the distance for the next star
            }
        }
        printf("\n");

        // Check if length is equal 3, else length -1 to get the correct rows of second half of the diamond
        if (diamondlength == 3) {
            // Loops until the first half of the diamond is finished, then reverse the process to print the second half
            if(i < (diamondlength - diamondlength / 3)) {
                space--;
                star++;
            } else {
                space++;
                star--;
            }
        } else if (diamondlength >= 3) {
            if (i < (diamondlength - 1 - diamondlength / 3)) {
                space--;
                star++;
            } else {
                space++;
                star--;
            }
        }
    }
}

实际运行结果:

actual result

预期结果:

Expected result

1 个答案:

答案 0 :(得分:2)

您用于计算空间的公式已关闭。当我更改此设置时对我有用

space = diamondlength;

对此

space = diamondlength/2+1;

还有这个

for (k = 0; k < numberOfDiamonds; k++) {
    for (j = 0; j < space; j++) {

对此:

for (k = 0; k < numberOfDiamonds; k++) {
    for (j = 0; j < space-1; j++) {

在这种情况下,我建议对不同的参数对该变量进行硬编码,并写下该变量对于什么参数的含义,以便您可以尝试找到将参数映射到值的函数。例如,我看到随着diamondlength的增加,空间误差也增加,因此参数和变量之间的关系不能一对一。