digit after decimal point!

I need to use digits after decimal point for my next calculations but I don't know how!
this is what i came up with:
(this program gets user input(distance) and divide it by 111(g1 and g2).)
1
2
3
4
5
6
7
     int distance,g1;
    double g2,sub;
    cin>> distance;//example:200 

    g1=(abstand/111); //200/111=1 (int)
    g2=(abstand/111);//200/111=1,80180 (double)
    sub=(g2-g1); //what I need : 0,80180 

but this code doesn't work! (sub=0)
can you find the problem?
or is there a better way?
( i hope it's clear what i mean)
i added
#include<iomanip>
and
cout << fixed << setprecision(6) << sub;
but still it doesn't work!(sub=0)
I don't know what the type or value of abstand is. However, if it is an int, since 111 is an int then integer division will be done, giving an integer result. Storing that result afterwards in a type double doesn't change that, since the calculation has already been completed.

If either or both of the values used in the calculation are floating-point-type, then floating-point division will be done. Here for example, use 111.0 (double) instead of 111 (int).
This is integer division: g2=(abstand/111);

To get a floating point result: g2 = double(abstand) / divisor ;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <limits>
#include <iomanip>

unsigned long long ipow( unsigned int b, unsigned int p ) { return p == 0 ? 1 : b * ipow( b, p-1 ) ; }

long long fractional_part( double dbl, unsigned int ndigits = 11 )
{
    ndigits = std::min( std::numeric_limits<long long>::digits10 - 1, int(ndigits) ) ;
    return std::llabs( std::llrint( ( dbl - std::trunc(dbl) ) * ipow( 10, ndigits ) ) ) ;
}

int main()
{
    const int divisor = 111 ;
    const int digits_after_decimal = 5 ;

    int abstand ;
    std::cin >> abstand ; // example: 200

    const int g1 = abstand / divisor ;
    const double g2 = double(abstand) / divisor ;
    const int sub = fractional_part( g2, digits_after_decimal ) ;

    std::cout << "abstand: " << abstand << "\ndivisor: " << divisor << "\ng1: " << g1
              << "\ng2: " << std::fixed << std::setprecision(15) << g2
              << "\nsub: " << sub << " (to nearest " << digits_after_decimal << " digits)\n" ;

    std::cout << "std::setprecision, (g2 - g1): " << std::setprecision(digits_after_decimal) << g2 - g1 << '\n' ;
}

http://coliru.stacked-crooked.com/a/62da8976ae6238e6
Last edited on
closed account (48bpfSEw)
By the way, a division can be presented as a sum of potencies with a lot of digits after the decimal points as you like.

Here is my discovery:

https://necips8.wordpress.com/2016/05/24/division-4/

Last edited on
thank you everyone!
it works now :)
abstand is actually the same word as distance,I forgot to change that.
Topic archived. No new replies allowed.