我正在尝试调试作业程序。对我来说看起来不错,但似乎无法正常工作。
这是任务:{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;
}
问题:
答案 0 :(得分:2)
我无法重现“为什么不断要求第二个E”这一点。
然而,“为什么无论结果为何都将零打印为零”是因为您将&E
和&sum
传递给printf
;即,您正在传递期望浮点值的指针,从而产生未定义的行为。相反,写
printf("The sum of sequence's elements above %f is: %f\n\n", E, sum);