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
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