typecasting

#include <iostream>
using namespace std ;

main () {


int i=3,j=2;
double k =static_cast<double>i/j;


cout<<k<<endl;



}


is there something wrong on this code ?
is there something wrong on this code ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std; // <-- for experts only; I (nearly) always avoid this.

int main () // main() must be int
{
    int i = 3, j = 2;

    // Since both i and j are ints, what you obtain is an integer division.
    // It returns an integer, and what you are explicitly converting to
    // double is the integer result.
    // If you want to obtain a 'real' double, you need to cast to double
    // at least one of those two int *before* performing the division.
    double k = static_cast<double>(i/j); // parenthesis were missing
    cout << "k: " << k << endl;

    k = static_cast<double>(i) / j;
    cout << "k: " << k << endl;

    k = i / static_cast<double>(j);
    cout << "k: " << k << endl;
}

Output:
k: 1
k: 1.5
k: 1.5

Topic archived. No new replies allowed.