Sum of cubes giving wrong answer?

May 18, 2015 at 1:50am
The following is the program im trying to write:

Write a program that asks the user to type an integer N and computes the sum of the cubes from 5^3 to N^3.

My only problem is that the answer printed to the screen is always 1 less than the correct answer, and I can't figure out why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int N, a, sum=0;

    cout << "Type in any integer greater than 5:" << endl << endl;
    cin >> N;
    while(cin.fail() || N<=5)
    {
        cout << "Invalid Entry. Try again:" << endl;
        cin.clear();
        cin.ignore();
        cin >> N;
    }

      for(int i=5; i<=N; i++)
      {
        a = pow(i, 3);
        sum+=a;
      }

    cout << "\n\nSum of the subes from 5 to " << N << " is: "
        << sum << "\n\n";

}



What am I doing wrong here?
May 18, 2015 at 2:00am
Based on cpp.sh, it is correct?

What do you mean "lesser by 1"? Like 5^3 to 6^3 is 340? I ran it and it computes 341.
Last edited on May 18, 2015 at 2:02am
May 18, 2015 at 2:10am
Your code worked for me. I used 6, 7, 8, 9, and 10 for N and it was right every time.
Last edited on May 18, 2015 at 2:10am
May 18, 2015 at 3:27am
Thats weird, it comes out as incorrect for me.

I just tried 6 and 7 and 10, and the output is always 1 less than the correct answer i.e. If I enter a 7, output is 683 when it should be 684.

Why are you guys getting the correct answer and im not?
May 18, 2015 at 3:36am
I just ran it in the cpp shell. Its works fine there.

However, if I run it in my codeblocks compiler, I always get an output 1 less than the correct answer.

Any idea why this is happening?
May 18, 2015 at 3:40am
I have no idea. I ran it visual studio and it worked fine.
May 18, 2015 at 9:50am
See "EXERCISE 6": http://en.wikibooks.org/wiki/C%2B%2B_Programming/Exercises/Iterations


I just tried the first solution and the output comes out fine. I enter a 6 and the output is 341.


But as soon as I run my own program, the output comes out wrong, always 1 less than the correct answer.

Is there something wrong with my code? But then how does it work for others?

Im really curious as to whats happening here. Any help would be appreciated.
May 18, 2015 at 9:57am
What editor and compiler are you using?
Last edited on May 18, 2015 at 9:57am
May 18, 2015 at 9:58am
CodeBlocks 12.11
Topic archived. No new replies allowed.