I have stumbled upon quirky C++ behavior that I cannot explain.
I am trying to calculate the dimensions of an image when resizing it (maintaining its ratio) to fit as much screen as possible. The x, y variables are dimensions of the image and X, Y variables are dimensions of the screen. When the resulting dimensions are not integers, I need to round them using standard rules of mathematics.
This program for inputs 499999999999999999 10 1000000000000000000 19
gives the (incorrect) answer of 950000000000000000 19
.
#include <iostream>
#include <cmath>
#include <algorithm>
int main()
{
long long x, y, X, Y;
std::cin >> x >> y >> X >> Y;
long double ratio = std::min((long double)X/x, (long double)Y/y);
x = round(ratio*x);
y = round(ratio*y);
std::cout << x << " " << y << std::endl;
return 0;
}
However, code below (only change is using namespace std;
and removing std::
from main
function body) gives the correct answer of 949999999999999998 19
.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
long long x, y, X, Y;
cin >> x >> y >> X >> Y;
long double ratio = min((long double)X/x, (long double)Y/y);
x = round(ratio*x);
y = round(ratio*y);
cout << x << " " << y << endl;
return 0;
}
I am using g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
and compiling the program with g++ -std=c++17 -Wall -Wextra -Wshadow
.