-1

Working with a friend, I was trying to debug why log10(1/4) returns -inf, while log10(0.25) returns the proper answer of -0.60206.

I was using this program to test it, and tried moving the values to variables.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{  
   double t = 1/4;
   double r = 0.25;
   cout << log10(t) << endl;
   cout << log10(r) << endl;

   return 0;
}

That returned -inf and -0.60206.

Why would 1/4 not behave the same as 0.25?

Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55

3 Answers3

2

1/4 is integer division, and the result is 0, which is then assigned to t. The conversion to double doesn't occur until after the result's been calculated already. To force floating point division and get 0.25, use 1.0/4.

This would have been fairly obvious if you tried printing out the value stored in t rather than just log10(t).

T.C.
  • 133,968
  • 17
  • 288
  • 421
1

Because 1 is an int, and 4 is an int, so it is the same as:

int one = 1;
int four = 4;
double x = one / four; // zero

Conversion from int to double happens at the end, after division has already taken place.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
1

In C++ (and most other programming languages), the division of an integer by an integer is always an integer. The result of 1/4 is truncated to produce 0.

Try 1.0 / 4 instead, as a float divided by an integer is always a float.

Vortico
  • 2,610
  • 2
  • 32
  • 49