代码看起来不错,但为什么它两次要求 E 并不断打印 0.000?

  • 本文关键字:两次 打印 看起来 代码 c
  • 更新时间 :
  • 英文 :


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

任务如下:{Xn} = |COSn|/n ---->0是限制为"0"的算术序列。目标是计算所有序列的元素总和,直到第 n 个元素的绝对值变为

这是代码:

/* {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: %fnn", &E, &sum);
return 0;
}

问题:

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

我无法重现"为什么它总是要求第二个E"的事情。 然而,"为什么无论如何它都会打印零"是因为您将&E&sum传递给printf;即,您正在传递预期浮点值的指针,从而产生未定义的行为。 相反,写

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

最新更新