how to split a number into the whole integer part and the decimal part?

closed account (j1AR92yv)
For my assignment,I have to write two functions, one called integer and the other decimal.

For decimal i have
double decimal;
cin >> decimal;
double whole = floor(decimal);
double decima = decimal - whole;
cout << decima << "\n";
cin.get();

But for the integer part, I don't know where to begin.
Last edited on
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
#include <iostream>

int integer( double value ) {

    // conversion from floating point to integer truncates towards zero.
    // (the fractional part is simply discarded).
    // conversion of 3.56 to int yields 3 and conversion of -23.99 to int yields -23
    // assumes that the result (value converted to int) is within the range of int
    return value ; // return result of converting 'value' to int
}

// return the decimal portion of the number as a non-negative value.
double decimal( double value ) {

    // if value == -23.99, then value = -value ; value == -(-23.99); value = +23.99
    if( value < 0 ) value = -value ; // make it non-negative

    // 3.56 - integer(3.56) == 3.56 - 3 == 0.56
    // 23.99 - integer(23.99) == 23.99 - 23 == 0.99
    return value - integer(value) ;
}

int main() {

    std::cout << integer(3.56) << '\n' // 3
              << integer(-23.99) << '\n' // -23

              << decimal(3.56) << '\n' // 0.56
              << decimal(-23.99) << '\n' ; // 0.99
}
Topic archived. No new replies allowed.