Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя fixme

Автор fixme, 14 лет назад, По-английски
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
  • Проголосовать: нравится
  • +9
  • Проголосовать: не нравится

14 лет назад, # |
Rev. 3   Проголосовать: нравится +1 Проголосовать: не нравится
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...
14 лет назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится
Spoiler in revision
14 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится
Yeah...
Super typo :)
  • 14 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    Thanks for the comment, but next time please post a comment in the English mode!  Otherwise it is not shown in the English version of the website (which seems to be a misfeature).
14 лет назад, # |
  Проголосовать: нравится +2 Проголосовать: не нравится
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.
  • 14 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    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.