-1

Problem 138

Basically, its asking for isosceles triangles where the height of the triangle is equal to base +- 1. After doing some math on paper, I use either of the following two equations to calculate the length L given b:

L = sqrt(1.25b2 + 2b + 1), substituted h with b + 1

or

L = sqrt(1.25b2 - 2b + 1), substitued h with b - 1

My following code calculates L from b using both equations. I sum up all the L values but it keeps giving me the incorrect answer.

#include <iostream>
#include <cmath>

int main(int argc, char* argv[]) {
  int result = 0;
  int count = 0;

  for (int b = 1; count < 12; b++) {
    double x;
    double L = std::sqrt(1.25*b*b + 2*b + 1);

    if (std::modf(L, &x) == 0.0) {
      std::cout << count << ": b=" << b << ", L=" << (int)L << "\n";
      result = result + L;
      count++;
    } 

    L = std::sqrt(1.25*b*b - 2*b + 1);
    if (count != 12 && std::modf(L, &x) == 0.0) {
      std::cout << count << ": b=" << b << ", L=" << (int)L << "\n";
      result = result + L;
      count++;
    }
  }

  std::cout << "Solution: " << result;
  std::cin.get();
  return 0;
}

What am I doing incorrectly? I would like a hint not a solution... I feel like this should be giving me the correct answer.

4

1 回答 1

0

这是数值精度不足的情况。我只是复制了您的代码并根据我使用的是 64 位 ( double) 还是 80 位 ( long double) 算术得到不同的答案。当然,出于同样的原因,80 位的答案可能仍然是错误的……您必须使用精确(整数)算术来 100% 确定(并避免溢出)。

于 2012-09-15T22:09:46.317 回答