【问题标题】:Sum of N reciprocals[Division mistake] [duplicate]N倒数之和[除法错误] [重复]
【发布时间】:2016-02-02 11:21:42
【问题描述】:
#include <iostream>
#include <math.h>
#include <ctype.h>

using namespace std; 
int main()
{
  int n=0,tot=0;
  float sum = 0;
  float average = 0;
  float product = 1;


  cout<<"Type an integer and press Enter:\n";
  cin>>n;
  /*
     Your logic goes here
  */
  for(int i=1;i<=n;i++){
       cout<<sum<<endl;
       sum= sum+(1/i);
       product=product*1/i;
       tot++;
   }
  cout<<"Sum, product and average of reciprocals are:\n"; 
  cout<<sum<<endl;
  cout<<product<<endl;
  cout<<average<<sum/tot<<endl;
} 

任何人请告诉我我做错了什么,我的总和总是等于一,我不知道为什么。我输入 cout 并在每次迭代时打印出“1”。我的逻辑是对的,但有一些我找不到的错误。

【问题讨论】:

  • 1/i 将为所有大于 1 的 i 为 0。整数除法。

标签: c++


【解决方案1】:

下面一行

sum= sum+(1/i);

进行整数除法,i = 1 时为 1,否则 i > 1 时为 0。我会使用 1.0/i 强制浮点除法

编辑:我也会更改您的 product 更新

【讨论】:

    【解决方案2】:

    对于大于 1 的所有 i1/i 将为 0。整数除法。您需要通过将1/i 替换为1.0/i 来解决此问题。

    见ideonehere

    【讨论】:

      猜你喜欢
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2015-01-27
      • 2011-05-29
      • 2012-11-12
      相关资源
      最近更新 更多