Hi

I am facing problem using float

in loop its value stuck at 8388608.00

int count=0;
    long X=10;
    cout.precision(flt::digits10);
    cout<<"Iterration #"<<setw(15)<<"Add"<<setw(21)<<"Mult"<<endl;
    float Start=0.0;
    float Multiplication = Addition * N;
    long i = 1;
    for (i; i <= N; i++){
        float temp = Start + Addition;
        Start=temp;
        count++;
        if(count%X==0 && count!=0)
        {
            X*=10;
            cout<<i;
            cout<<fixed<<setw(30)<<Start<<setw(20)<<fixed<<i*Addition<<endl;
        }
    }

what should i do??

What is N?

I am facing problem using float
in loop its value stuck at 8388608.00

First read up a bit on the representation of floating point numbers and loss of precision.
http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html

Then, try out this program:

#include <limits>
#include <iostream>
#include <iomanip>

int main()
{
    typedef std::numeric_limits<float> limits ;
    std::cout << "exponent ranges from: " << limits::min_exponent << " to "
              << limits::max_exponent << " binary ie. about "
              << limits::min_exponent10 << " to " << limits::max_exponent10
              << " decimal\nmantissa has " << limits::digits << " binary digits "
              << "ie. about " << limits::digits10 << " decimal digits\n" ;

    const unsigned long long max_mantissa = ( 1U <<  (limits::digits-1) ) - 1 ;
    std::cout << std::fixed << std::setprecision(limits::digits10)
              << "max value of normalised mantissa: " << max_mantissa << '\n' ;

    float big = max_mantissa ;
    float small = 0.1 ;

    float a = big, b = small, c = -a ;
    std::cout << "a == " << a << '\n' ;
    std::cout << "b == " << b << '\n' ;

    std::cout << "a+b == " << a+b << '\n' ;
    std::cout << "a-b == " << a-b << '\n' ;
    std::cout << "a+b+c == " << a+b+c << '\n' ;
    std::cout << "a+c+b == " << a+c+b << '\n' ;
}

Can you explain the output?

This is the output on my implementation:

exponent ranges from: -125 to 128 binary ie. about -37 to 38 decimal
mantissa has 24 binary digits ie. about 6 decimal digits
max value of normalised mantissa: 8388607
a == 8388607.000000
b == 0.100000
a+b == 8388607.000000
a-b == 8388607.000000
a+b+c == 0.000000
a+c+b == 0.100000

thanks :)

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.