In depth analysis of C++ two large Numbers multiplied incorrectly

  • 2020-04-01 23:35:44
  • OfStack

When I wrote the code for the test, I found that the result of multiplying two large Numbers was incorrect. The test code is as follows:
# include "stdafx. H"
# include < Stdlib. H >
# include < Time. H >
Int _tmain(int argc, _TCHAR* argv[])
{  
      Time_t temp1 = 1345172428000000;
      Time_t temp2 = 1345172428 * 1000000;
    : : system (" pause ");
      Return 0;
}
After testing, it was found that temp1 and temp2 are not equal.
But changed to the following code:
# include "stdafx. H"
# include < Stdlib. H >
# include < Time. H >
Int _tmain(int argc, _TCHAR* argv[])
{
      Time_t temp1 = 1345172428000000;
      Time_t temp3 = 1345172428;
      Time_t temp4 = 1000000;
      Time_t temp2 = temp3 * temp4;
      : : system (" pause ");
      Return 0;
}
After testing, temp1 and temp2 are found to be equal.
Analysis reasons:
      Both 1345172428 and 1000000 are treated as int, and the result of multiplying them is also treated as int, only the product will be cast to time_t, but the product will overflow when the product is calculated, so the conversion to time_t is also wrong.
Conclusion:
      The product overflow problem should be considered in the multiplication of large Numbers.

Related articles: