简体   繁体   English

在 C 中打印数字模式

[英]Printing number patterns in C

I'm still learning loops and Number pattern in C and I tried to execute this pattern as an exercise:我仍在学习 C 中的循环和数字模式,并尝试将这种模式作为练习来执行:

98765
87654
76543
65432
54321

The maximum number in the pattern is 9 and the minimum number is 1. So I did this:模式中的最大数字是 9,最小数字是 1。所以我这样做了:

#include <stdio.h>
   

int main() {
    int i,num,x=9,y,z;

    scanf("%d", &i);

    for (z=1;z <= i; z++) {
        num=x;
        x--;
         
         for (y = 1; y <= i; y++) {
             printf("%d",num);
             num--;
         }
         printf("\n");
    }

    return 0;
     
}

The number of rows and columns should be the same as well.行数和列数也应该相同。 I still need help in figuring out what is lacking.我仍然需要帮助来弄清楚缺少什么。

I didn't understand your question fully, make your question clear first.我没有完全理解你的问题,先把你的问题说清楚。

But if you want to print a pattern of number with equal num of rows and column and you are taking both the higher number and lower num as input then maybe the code shown here will work for you.但是,如果您想打印具有相等行数和列数的数字模式,并且您将较高的数字和较低的数字作为输入,那么这里显示的代码可能对您有用。

#include <stdio.h>
    
int main() 
{
    int biggerNumber = 9, smallerNumber = 1;
    
    int numberOfRowAndColumn = ((biggerNumber - smallerNumber) / 2) + 1;
    for (int i = 0; i < numberOfRowAndColumn; i++)
    {
        int temporaryVariable = biggerNumber;
        biggerNumber--;

        for (int j = 0; j < numberOfRowAndColumn; j++)
        {
            printf("%d ", temporaryVariable);
            temporaryVariable--;
        }
        printf("\n");
    }
    return 0;
}

And if you want to take numbers of rows and column from user than you can do that too, by just changing one line.而且,如果您想从用户那里获取行数和列数,那么您也可以这样做,只需更改一行即可。

  int numberOfRowAndColumn = ((biggerNumber - smallerNumber) / 2) + 1;

instead of this line just write而不是这一行只写

 scanf("%d", &numberOfRowAndColumn);

to take input from user.从用户那里获取输入。

Hope this helps.希望这可以帮助。

This is the output of code shown above:这是上面显示的代码的输出:

9 8 7 6 5 
8 7 6 5 4 
7 6 5 4 3 
6 5 4 3 2 
5 4 3 2 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM