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).
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…