简体   繁体   English

系列:1 + 1/3 + 1/5 +…最多 N 项

[英]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.

相关问题 如何打印最多n个术语的序列,每个术语=前三个术语的总和,第一个术语= 1,然后2 3 6 11 - How to print a series upto n terms, with each term = sum of previous three terms and first term=1 then 2 3 6 11 我们如何使用 C 中的递归将系列 1+ 11 +111+... 的总和打印到 N 项 - How can we print the sum of series 1+ 11 +111+… upto N terms using recursion in C 如何在 c 中打印最多 50 个项的斐波那契数列? - How to print fibonacci series upto 50 terms in c? 编写程序以生成序列中的前n个项-34,18,10,6,4, - Write a program to generate the first n terms in the series — 34,18,10,6,4, 为什么通过添加无限级数的前 N 项来计算 sin(x) 总是返回 0.00000? - Why does calculating sin(x) by adding the first N terms of an infinite series always return 0.00000? 生成直至给定数字N的步进数 - Generate stepping numbers upto a given number N 找到选择加起来为n的k数的方法的数量 - Finding number of ways to select k numbers that add upto n 查找高达给定值n的质数的优化方法 - Optimized way for Finding prime numbers upto given value n 读到EOF,但执行每行直到\\ n - Read till EOF but exec every line upto the \n 如何打印此系列?(1 \\ n 2 3 \\ n 4 5 6 \\ n 7 8 9 10……) - How to print this series?(1 \n 2 3 \n 4 5 6 \n 7 8 9 10… … …)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM