double value to int value

Trying to write a program which returns the integer part of any number passed to a function. having some trouble with this program any help would be appreciated. thank you.

This is what i've got right now.

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double whole(double,int&);
int main()
{
double numDec;
int numInt;
cout<<" Please enter a number. ";
cin>>numDec;
whole(numDec,numInt);

cout<<" The integer part of this number is "<<numInt<<"."<<endl;
system("pause");
return 0;
}
double whole(double numDec,int& numInt)
{
numDec=numInt;
return numInt;
}

Please use code tags in the future.

Primitive type deprecation into an integer from a double will do this.

double d = 12.34;
int i = (int) d;

You only needed to add 1 line of code in your "whole(...)" function, I suggest you think things out yourself before you start asking questions which is basically done. You have mixed up integer variables with doubles..

1
2
3
4
5
6
void whole(double, int&);
...
void whole(double d, int& i)
{
   i = (int) d;  //Wow that was hard
}


Your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
 #include<iomanip>
 #include<cmath>
 using namespace std;
 double whole(double,int&);
 int main()
 {
    double numDec;
    int numInt; //Ok declared a variable with no value, look further down
    cout<<" Please enter a number. ";
    cin>>numDec;
    whole(numDec,numInt);

    cout<<" The integer part of this number is "<<numInt<<"."<<endl;
    system("pause");
    return 0;
 }

 double whole(double numDec,int& numInt)
 {
    numDec=numInt;  //But you never set numInt, only numDec, not assigning a foreign type with an unset value
    return numInt;  //Why would you return an integer, with no value, as a double
 }

I can only assume you're getting the assignment '=' operator mixed up.
destination = source;
Last edited on
Thanks for the help man, i've only been taking the class for about 2 weeks still pretty new at it. And have never seen this (int) function so far in the class. But it works so like I said thank you.
this (int) function

Technically, it's not a function; it's an explicit type cast. It's basically saying "I know 'd' is a double, but please make it an int for me". Casting a double (or float) to an int simply truncates the decimal part away.
Just think of (int) as a shortened static_cast<int>().
Topic archived. No new replies allowed.