[英]Series: 1 + 1/3 + 1/5 +…upto N terms
I was recently asked this question in a programming test.我最近在编程测试中被问到这个问题。 I can't seem to understand why I am getting the answer '1'.我似乎无法理解为什么我得到的答案是“1”。 I am a beginner in the C
programming language.我是C
编程语言的初学者。
Here is my code:这是我的代码:
#include<stdio.h>
int main()
{
float c = 0;
int n, i = 1;
printf("Enter the number here: ");
n = getchar();
while (i <= 2*n - 1)
{
c = c + (1/i);
i = i + 2;
}
printf("%f", c);
}
I have already tried using a for
loop, but the answer remains the same.我已经尝试过使用for
循环,但答案保持不变。 Any help would be appreciated!任何帮助,将不胜感激!
The problem in your code lies on this line:您的代码中的问题在于这一行:
c = c + (1/i);
Here, the operation performed inside the parentheses is integer division, So, when i
has any value greater than 1
, the result will be zero.这里,括号内执行的操作是integer除法,因此,当i
有任何大于1
的值时,结果将为零。 This zero is then converted to a float value.然后将此零转换为浮点值。
To force the compiler to use floating point division, use this:要强制编译器使用浮点除法,请使用以下命令:
c = c + (1.0/i);
I agree with Adrian's answer.我同意阿德里安的回答。
Another issue is because of the way floating point numbers are represented in a system when they are added in arbitrary order, precision can be lost.另一个问题是由于浮点数在系统中以任意顺序添加时的表示方式,可能会丢失精度。
To have maximum precision, floating point numbers should be added from smallest first to largest last.为了获得最大精度,浮点数应该从最小的第一个到最大的最后一个添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.