首页 > 解决方案 > 有没有一种有效的方法可以在 C 中构建正负数模式?

问题描述

嘿,我是 C 编程的新手,目前我正在自学,并从一些尚未回答的大学模块中找到了这个任务。问题是打印以下模式:

Input N = 3                   Input N = 4

Output                        Output
    1  -3   5                     1  -3   5  -7
   -2   4  -6                    -2   4  -6   8
    1  -3   5                     1  -3   5  -7
                                 -2   4  -6   8

我已经尝试写了,但我找不到适合这种模式的最佳条件。这是我的代码

    #include <stdio.h>
int even(int input)
{
    int num;
    for(int i=2; i<=input*2; i+=2) {
        if (i == 2)
            printf("%d ", i * -1);
        else {
            if (i/2 <= 3 && i/2 >=2)
                printf("%d ", i * -1);
            else
                printf("d ",i);
        }
    }
}
int odd(int input)
{} /* i haven't code for the odd one yet because its almost similar with the even*/

int main ()
{
    int N;
    puts("provide N: ");
    scanf("%d",&N);
    even(N);
    odd(N);
    return 0;
} 

结果在这里显示 结果

Provide N:
3
Result :
-2-4-6

我应该在哪条线上工作?

标签: cif-statementnested-loops

解决方案


不需要的话。只有简单的数学

#include <stdio.h>

void printPattern(int x)
{
    for(int row = 0; row < x; row++)
    {
        int neg = -1 + 2 * (row % 2);
        for(int num = 1; num <= x * 2; num += 2) 
            printf("%d ", (num + row % 2) * (neg *= -1));
        printf("\n");
    }
}

int main(void)
{
    printPattern(4);
}

https://godbolt.org/z/PvcWcP


推荐阅读