首页 > 解决方案 > 如何在C中的整数数组中添加二次序列

问题描述

我正在尝试在整数数组(在 C 中)中添加一个二次序列,而不是手动输入它。

#include <stdio.h>

    int main () 
    {    
    int x [100] = {0, 50, 150, 300, 500, 750, 1050, 1400};
                //+0, +50, +100, +150, +200, +250, +300, +350, etc.
    return 0;
    }

有没有办法做到这一点?

标签: carraysintegersequence

解决方案


num_add 在每个循环中添加 50。

#include <stdio.h>

int main() {
    int x[100];
    int num_add = 50;
    x[0] = 0;
    for (int i = 1; i < 100; i++) {
        x[i] = x[i - 1] + num_add;
        num_add += 50;
    }
    for (int i = 0; i < 100; i++) {
        printf("%d ", x[i]);
    }
    return 0;
}

推荐阅读