【问题标题】:What is the error?Q-To determine and print the sum of the following harmonic series for a given value of n.(1+1/2+1/3+........+1/n) [duplicate]错误是什么?Q-确定并打印给定 n 值的以下谐波级数之和。(1+1/2+1/3+........+1/n) [复制]
【发布时间】:2018-12-14 10:22:15
【问题描述】:
void main()  
{  
    int n,i;  
    printf("enter number");  
    scanf("%d",&n);  
    float s=0;  
    for(i=1;i<=n;i++)  
    {  
        s=s+(1/i);  
    }  
    printf("sum is %f",s);  
}  

我得到 1.00 的输出。为什么?

【问题讨论】:

  • 因为 1/2 是 0。 int / int = int. int / float = 浮动。

标签: c++ c loops c++11 for-loop


【解决方案1】:

试试这个....

void main()  
{  
    int n,i;  
    printf("enter number");  
    scanf("%d",&n);  
    float s=0;  
    for(i=1;i<=n;i++)  
    {  
        s=s+(1.0/i);  
    }  
    printf("sum is %f",s);  
} 

如果有 int/float,那么预期的结果将是 int。如果你想要准确的浮点结果,那么你必须做浮点/浮点

【讨论】:

  • 虽然正确,但这需要一些解释。也可以考虑先添加小项。
猜你喜欢
  • 2011-01-29
  • 2021-12-30
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 2020-01-10
相关资源
最近更新 更多