如何输出此数字序列?

问题描述 投票:0回答:1

示例:

enter a number:5
output : 5,10,15,20,25,20,15,10,5

**Example 2:**
enter a number :3 output : 3,6,9,6,3

代码:

#include<stdio.h>
void main(){

    int a,i ;
    a=5;
    i=1;

    do{
        printf("%d\t",a*i);
        i++;

    }
    while(i<=5);
int b,l;
    b=3;
    l=1;

    do{
        printf("\n%d\t",b*l);
        l++;
    }
    while (l<=3);
}

[请帮助我使用我的代码,以便改善自己并显示正确的结果,应该先增加然后减少给定的数字。

c stdio
1个回答
0
投票

要打印这些类型的序列,您还可以使用递归。您的函数将如下所示:

void printSequence(int x, int incr)
{
    if (x == incr * incr)
    {
        printf("%d ", x);
        return;
    }

    printf("%d ", x);
    printSequence(x + incr, incr);
    printf("%d ", x);
}

因此,您将开始编号和增量发送给该功能。在您的情况下,它们将是相同的数字,因为您想以5开头,然后将其递增5,直到您达到5 * 5。最基本的情况是,您的数字x等于x*x,在代码中以x == incr * incr表示。如果您的基本情况是正确的,则只需打印出x的当前值并从函数中返回即可。如果您的基本情况不正确,则要打印出x的值并以x为增量再次调用同一函数。然后,当您递归开始从上一个函数调用返回到原始函数调用时,再次打印x的值。

如果您的主体看起来像这样:

int main(void)
{

    printSequence(5, 5);

    return 0;
}

输出将是:

5 10 15 20 25 20 15 10 5

© www.soinside.com 2019 - 2024. All rights reserved.