#include <iostream>
using namespace std;
int main()
{
  int i,j;
float a[10][10];

 for (i=0; i<10; i++)
    {
      for (j=0; j<10; j++)
        {
          a[i][j]=0.2;
          a[i][j]=a[i][j]-0.2;
          cout<<a[i][j]<<"\n";
        }
    }

}

////
why is the output not exactly 0.00 ???
how do i make it output 0.00

This is due to the processor precision during the computations. With float variables, it is about 7 digits. See http://www.cplusplus.com/doc/tutorial/variables/. At the processor level, the binary substraction of a constant from a variable is not performed in exactly the same way as the substraction of a variable from another variable. To prove this define a new variable

float b=0.2;

and replace the instruction

a[i][j]=a[i][j]-0.2;

by

a[i][j]=a[i][j]-b;

The output is not exactly 0.0 because floating-point values on a computer can NEVER be exact. You can format the output such that it doesn't display in scientific notation (like with a big negative exponent, as I assume it does now).

I beg to differ with both of the previous posters.

Most computers these days (including, so far as I know, all currently manufactured Intel processors) use IEEE floating point, which requires that the results of floating-point addition, subtraction, multiplication, division, and square root be deterministic. In particular, the IEEE standard requires that the result of any of these operations be bit-for-bit identical with what the result would be if the operation were conducted in infinite precision and then rounded (according to the current rounding mode) to the given precision.

The standard does permit intermediate results to be computed in greater precision than the variables involved in the computation, but that liberty does not affect the program shown here.

The real reason that the output from this program is surprising is simpler: The type of the literal 0.2 is double, not float. Moreover, the value 0.2 cannot be precisely represented in an IEEE floating-point number.

Therefore, when we write

float x = 0.2;
float y = x - 0.2;

the value of x - 0.2 is computed by converting x to double, subtracting the double representation of 0.2 from it, and converting the result back to float. The result is to make y equal to the difference between the float representation of 0.2 and the double representation.

If you were to change the program as follows:

double x = 0.2;
double y = x - 0.2;

then I believe that the IEEE standard would require a conforming implementation to yield a value of exactly 0 for y, and I would be surprised if you could find a computer in current manufacture and widespread use that does not behave this way.

thx a lot for help me !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.