简体   繁体   English

C 数学求解和代码结果的程序差异

[英]C program difference between mathematical solve and code result

I like to calculate the following formula using c programming.我喜欢使用 c 编程来计算以下公式。 The formula is as follows:公式如下:

在此处输入图像描述

I have written the c program based on this formula我根据这个公式编写了 c 程序

#include<stdio.h>
#include<math.h>
int main(){
     int n,i;
     double sum=0;
     printf("Enter the value for n");
     scanf("%d",&n);
     for (i=0; i<=n; i++){

     sum = sum + 4*(pow(-1,i))/((2*i)+1);
     }
     printf("sum of the series: %lf",sum);
}
return 0;

I am sharing the result that I have got after run the program and the result I got while calculating the result mathematically.我正在分享我在运行程序后得到的结果以及我在数学计算结果时得到的结果。

在此处输入图像描述

在此处输入图像描述

As you can see from picture 1 if I try to calculate the sum for different value of n like 1, 4,13 the sum was 2.67, 3.339, 3.0702 respectively.正如您从图 1 中看到的那样,如果我尝试计算 n 的不同值(如 1、4、13)的总和,总和分别为 2.67、3.339、3.0702。

However, when I tried to calculate this formula mathematically I got some different result.然而,当我试图用数学方法计算这个公式时,我得到了一些不同的结果。

Mathematically I got数学上我得到了

n= 1 ans: 3.2 n = 1 答案:3.2

n=4 ans: 0.96825 n=4 答案:0.96825

Can anyone please guide what I am missing in code?谁能指导我在代码中遗漏的内容?

Thank you.谢谢你。

In 2nd iteration of your manual calculation, 2x1 + 1 = 3 but you're taking it as 5在您的手动计算的第二次迭代中,2x1 + 1 = 3 但您将其视为 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM