double i,j,k;

k=(i%j);


The program generates a error in second line and compiler show a message I can not use % in double variable. But I need to separate the each digit of a double variable how I can do this?

Member Avatar for JSPMA1988

Try spacing everything out? And maybe try initializing all three variables to zero out of good practice.

Maybe use sprintf, thanks to it you can have digits in char table.

But I need to separate the each digit of a double variable how I can do this?

A floating-point representations is inexact; so very often you can compute a more accurate result of an operation on real numbers in your head than your computer can do with floating-point numbers. When it comes to 'each digit of a double variable' (where by 'digit' you mean 'decimal digit'), things get even murkier. The floating-point representation of a real number typically uses a radix of 2; though the external representation is decimal (to base 10). We expect 0.01 to be exactly representable; the digits are 0, 0, and 1 followed by zeroes. However 0.01 may not be exactly representable (in limited memory) using a binary radix.

With those caveats in place, write out the double value (to the precision that you require) to a std::ostringstream and pick off the digits from the characters in the std::string.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <locale>

int main()
{
    double a = 10.35 ;
    std::cout << std::fixed << std::setprecision(16) << a << '\n' ;

    std::ostringstream stm ;
    stm << std::fixed << std::setprecision(16) << a ;
    std::string str = stm.str() ;

    std::cout << "decimal digits: " ;
    for( std::string::size_type i = 0 ; i < str.size() ; ++i )
        if( std::isdigit( str[i], stm.getloc() ) )
        {
            int digit = str[i] - '0' ;
            std::cout << digit << ' ' ;
        }
    std::cout << '\n' ;
}
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.