2015-11-02 69 views
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; 
} 

任何人都請告訴我我做錯了什麼,我的總和總是等於1,我不知道爲什麼。我把cout和每次迭代打印出「1」。我的邏輯是對的,但有一些我找不到的錯誤。N倒數總和[劃分錯誤]

+3

'1/i'將爲0對於所有'i'大於1的整數除法。 – erip

回答

1

下面的行

sum= sum+(1/i); 

是否整數除法,當i = 1它將評價爲1,否則當I> 1,這將是0。我想使用1.0/i迫使浮點除法

編輯:我會做出改變你product更新以及

1

1/i將爲所有i克0整數除法。您需要用1.0/i替換1/i來解決此問題。

參見ideone here