代码看起来不错,但是为什么要问两次E并不断输出0.000?

时间:2018-10-10 17:26:59

标签: c

我正在尝试调试作业程序。对我来说看起来不错,但似乎无法正常工作。

这是任务:{Xn} = |COSn|/n ---->0是一个限制为'0'的算术序列。目的是计算序列中所有元素的总和,直到第n个元素的绝对值变为<然后是E(从用户那里获取)。

这是代码:

/* {Xn} = |COSn|/n - is a sequence programm works with*/

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

/* adding libraries here*/

float calele(float a) // A function to CALculate an ELEment
{
    float b;
    b = fabs( cos(a) )/a; // {Xn} = |COSn|/n
    return b;
}

float seqsum(float E) //function, that counts sum. 
                      //"calele" function is used
{
    int n=1;
    float sum = 0.0;
    while( fabs(calele(n)) >= E) //if absolute value of counted element is still >= then user's E
    {
        sum = sum+calele(n); // then we add it so sum
        n = n+1;
    }
   return sum; // as soon as counted element becomes < then user's E, programm stops and returns the sum
}

int main(void)
{
    float E = 0; // Declaring E's variable
    float sum = 0; // sum of sequence's elements

    printf("Enter sequense's lower limit: "); // Prompting the user for the E
    scanf("%f", &E); // Getting E from the user
    sum = seqsum(E); // counting sum via function above
    printf("The sum of sequence's elements above %f is: %f\n\n", &E, &sum);

    return 0;
}

问题:

  1. 为什么它不能正常工作?
  2. 为什么总是不断要求第二个E?
  3. 为什么无论什么结果都打印零?

1 个答案:

答案 0 :(得分:2)

我无法重现“为什么不断要求第二个E”这一点。 然而,“为什么无论结果为何都将零打印为零”是因为您将&E&sum传递给printf;即,您正在传递期望浮点值的指针,从而产生未定义的行为。相反,写

printf("The sum of sequence's elements above %f is: %f\n\n", E, sum);