N 倒数之和[除法错误]

Sum of N reciprocals[Division mistake]

本文关键字:除法 错误 倒数      更新时间:2023-10-16
#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"。我的逻辑是对的,但有一些错误我找不到。

下一行

sum= sum+(1/i);

做整数除法,i = 1时计算结果为1,否则当我>1时,它将为0。 我会用1.0/i来强制浮点除法

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

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

在此处查看 ideone