0
#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;
} 

Anyone please tell me what I am doing wrong , my sum is always equal to one, i don't know why. I put cout and at each iteration it printout "1". My logic is right but there is some mistake which i can't find.

John Sick
  • 427
  • 6
  • 15

2 Answers2

1

The following line

sum= sum+(1/i);

Does integer division, when i = 1 it will evaluate to 1, otherwise when i > 1, it will be 0. I would use 1.0/i to force floating point division

EDIT: I would make the change to your product update as well

sedavidw
  • 11,116
  • 13
  • 61
  • 95
1

1/i will be 0 for all i greater than 1. Integer division. You will want to fix this by replacing 1/i with 1.0/i.

See ideone here

erip
  • 16,374
  • 11
  • 66
  • 121