首页 > 解决方案 > 使用 c 的正弦系列

问题描述

我试图生成正弦级数的项并总结它们的值。但我面临着错误。因为我们有交替的 + 和 - 术语,所以我有两个 for 循环。接受这些值后,代码将停止工作。问题在于用于生成术语的 for 循环。由于数组部分工作正常。

#include <stdio.h>
#include <math.h>

int main() {
    int i, number, j, x, value, value1, sign = 0;
    float sum, sub, res, term = 0;
    int fact = 1;
    printf("Enter the number of terms:\n");
    scanf("%d", & number);
    int a[(number)];
    //Storing odd numbers in array for terms//
    for (i = 0; i <= (2 * number); i++) {
        if ((i % 2) != 0) {
            a[j] = i;
            j++;
        }
    }
    printf("Enter the value for x:");
    scanf("%d", & x);
    //Generating term//
    for (j = 0; j <= number;) {
        a[j] = value;
        value = value1;
        //Finding factorial//
        while (value > 1) {
            fact = fact * value;
            value = value - 1;
        }
        term = (pow(value1, j) / fact);
        sum = sum + term;
        j = j + 2;
    }
    for (j = 1; j <= number;) {
        a[j] = value;
        value = value1;
        //Finding factorial//

        while (value > 1) {
            fact = fact * value;
            value = value - 1;
        }

        term = (pow(value1, j) / fact);
        sub = sub - term;
        j = j + 2;
    }

    res = sum - sub;

    printf("%f", res);
    return 0;
}

标签: ctrigonometryseries

解决方案


变量value1在没有被初始化的情况下被使用。此外,它看起来像是打算更新的,但它从未在程序的任何地方分配。

value = value1;实际上应该分value1 = value;两种情况?

此外,valuesumsub第一次使用之前不会初始化为零。要在声明中初始化这些变量,您应该= 0为每个变量添加。


推荐阅读