double i,j,k;


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?

6 Years
Discussion Span
Last Post by vijayan121

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


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' ;

Edited by vijayan121: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.