fixme's blog

By fixme, 13 years ago, In English
The following C++ program is supposed to report the sum and the squared sum of the 16 numbers hard-coded in the program.  The sum is correct but the squared sum is incorrect.  Can you see the typo?

This typo is taken from a program which I wrote for a report about ten years ago when I was an undergraduate student.  The actual program did something more complicated, but the essence of the typo was the same as the one shown here.

> cat sum.cc
#include <stdio.h>

int main()
{
    static const double data[16] = {
        -8.0,  3.5,  4.0, -2.5,
         3.0,  0.5,  1.5, -6.0
        -1.5,  2.0, -2.5,  4.5,
         3.0, -7.0,  5.0, -1.0
    };

    double s = 0.0;
    double s2 = 0.0;
    for (int i = 0; i < 16; ++i)
    {
        s += data[i];
        s2 += data[i] * data[i];
    }
    printf("sum = %f, sum of squares = %f\n", s, s2);
    return 0;
}
> g++ -Wall -o sum sum.cc
> ./sum
sum = -1.500000, sum of squares = 280.750000
  • Vote: I like it
  • +9
  • Vote: I do not like it

13 years ago, # |
Rev. 3   Vote: I like it +1 Vote: I do not like it
Interesting, but I expected to see comma used as decimal separator since in Russia it is standart.

Here is spoiler in previous revision of comment...
13 years ago, # |
Rev. 2   Vote: I like it +1 Vote: I do not like it
Spoiler in revision
13 years ago, # |
  Vote: I like it +2 Vote: I do not like it
I added a printing statement in the for loop. The value of i goes from 0 to 15 as normal. But the value of data[i] gets wrong when i reaches 7. Look around the 8th element and I found the problem.
  • 13 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    That would have been the right thing to do.  Ten years ago I did not suspect an error in that part, and if my memory serves me correctly, it took me a good hour to fix the bug.