我的作业还有一个问题。这次我大致知道自己的位置,但我可以看到我的代码存在一些明显的问题。最近我丢了 key ,有点像这样。我不知道我的代码到底哪里出了问题,但我有一个好主意,我希望你能帮我找到它。
问题是使用泰勒级数来近似圆周率。 现在,我的问题不完全是让它近似等于 pi。 使用用户输入的前 N 个项 近似 pi 。因此,例如,如果我要输入 2,那么我应该运行前 2,因为 N=2。我的问题是 printF 表示它的方式(并且变量似乎未初始化)。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms;
int sign= 1;
int n;
float sum= 0.0;
float next_Term;
float final_sum;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&n);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
sum= sum+next_Term;
next_Term = sign*(1.0/(2*n-1));
sign = sign*-1;
}
final_sum = sum*4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}
最佳答案
I don't know exactly WHERE I went wrong with my code
首先,您将值扫描到变量 n 中,然后将其用作迭代器变量。将其更改为 num_Terms。这应该可以解决您不考虑项数的主要问题。
然后,最好在使用变量之前对其进行初始化,这样可以消除收到的警告。
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms = 0;
int sign = 1;
int n = 0;
float sum = 0;
float next_Term = 0;
float final_sum = 0;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&num_Terms);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
//not too sure if you need to reverse this order of calculation of sum
sum = sum + next_Term;
next_Term = sign * (1.0/(2*n-1));
sign = sign * -1;
}
final_sum = sum * 4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}
关于c - 近似Pi/Taylor级数;提示用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32900261/