Calculations do not work for every scenario

The equation I am trying to make a program for is (we cannot use cmath library and pow function):

sum = n/x^0 + (n-1)/x^1 + (n-2)/x^2 + (n-3)/x^3 + ...

x=number
n=terms you would like to calculate

example: x=6 and n=3

sum = 3/6^0 + 2/6^1 + 1/6^2
= 3/1 + 2/6 + 1/36
= 3.361
COMES OUT CORRECT

example: x=2 and n=6
should = 10.03125
but it is outputting = 9.69533

Please help me find my error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    
    float num;
    float term;
    float first;
    float total;
    float sum;
    
    cout<<"Please enter a number: ";
    cin>>num;
    cout<<"Please enter the number of terms you would like to calculate: ";
    cin>>term;
    
    first=(term-1)/num;
    for (int i=2;i<=term;++i){
        total+=(term-i)/(num*=num);
    }
    sum=term+first+total;
    cout<<sum<<endl;
    return 0;
}
Last edited on
Take a look at num and how its value changes.
I ran your program in my debugger and confirmed the issue.


example: x=6 and n=3

sum = 3/6^0 + 2/6^1 + 1/6^2

example: x=2 and n=6

sum = 6/2^0 + 5/2^1 + 4/2^2 + 3/2^3 + 2/2^4 +1/2^5

in math...

6/2^0 = 6 Exact (in decimal form)
5/2^1 = 2.5 Exact (in decimal form)
4/2^2 = 1 Exact
3/2^3 = 0.325 Exact (in decimal form)
2/2^4 = 0.125 Exact (in decimal form)
1/2^5 = 0.03125 Exact (in decimal form)

in c++ on my machine running my compiler

Before first run of your loop (with your input)

double num; num :2
double term; term: 6
double first; 4.9406564584124654e-324
double total; 0
double sum; 1.1590463849422306e-317

During the loop

Total after loop 1 : 1
Total after loop 2 : 1.1875
Total after loop 3 : 1.953125
Total after loop 4 : 1.1953277587890625
Total after loop 5 : 1.1953277587890625


Sum = term: 6 + first: 2.5 + Total: 1.195327758789025
Sum = 9.695327758789025


So that is why Your program is outputting that number.

What is the problem you are trying to solve? Can you post more information about that? Sorry, I cannot solve your issue at this point, my intuition about your actual program is not giving me a solution, I do hope that my post helps you tho.

@Peter87 might be on to the issue.
Topic archived. No new replies allowed.