Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

c++ - Arithmetic overflow: Using operator '*' on a 4 byte value then casting the result to a 8 byte value

I am trying to write a program to solve a quadratic equation whose coefficients' values do not exceed 100 by absolute value and it is guaranteed that if any roots exist, they are integers. Here's what I've tried:

#include <cmath>
#include <iostream>

int main() {
  int a, b, c;  // coefficients of quadratic equation
  std::cin >> a >> b >> c;
  int d = b * b - 4 * a * c;  // discriminant

  if (d < 0)
    std::cout << "No roots";
  else if (d == 0)
    std::cout << "One root: " << -b / (2 * a);
  else
    std::cout << "Two roots: " << (-b - std::sqrt(d)) / (2 * a) << " "
              << (-b + std::sqrt(d)) / (2 * a);

  return 0;
}

It works fine, however, Visual Studio 2019 shows this warning:

Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow (io.2).

enter image description here

Exactly why does this warning pop up and what is it trying to tell me? What am I doing wrong and how can I fix the problem?

I've seen this on SO, but I don't believe it's a bug.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The root cause here (pun very much accepted) is that the quadratic equation is not a Diophantine equation. It applies to real numbers, and in particular sqrt(d) is usually not an integer.

In C++, the return type of sqrt(IntegralType) is double. Thus 2*a is converted to double too, but only after multiplying. And Visual Studio very reasonably notes that you're better off doing the conversion before multiplying. It just doesn't note that you can even make a,b,c all doubles from the start.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...