static casting to double

closed account (Dz0RfSEw)
I have 2 numbers num1=251 and num2=45. I have to divide 251/45 and the answer has to be a double. How do I static cast this so it turns out to be a double?

Cast either one of the numbers to double, and the division will become floating-point division instead of integer division.
closed account (Dz0RfSEw)
I cast num1 to a double but the answer still comes out as an int and it says: " warning C4244: '=' : conversion from 'double' to 'int', possible loss of data"
Post your code and we can see what your doing.

To static cast it to a double you should do this:
1
2
int num1 = 251, num2 =45;
std::cout<<(double)num1/num2;


this gives you 5.7777778 which is the correct answer.
Maybe your storing the result of num1/num2 in some variable that is an int? That would give you an int result of 5 and not a double
Last edited on
closed account (Dz0RfSEw)
double Average(num1, num2);
void OutputAverage(ofstream& fout, double classAverage);


int main()
{
int num1= 251;
int num2 = 45;
double classAverage;


fout<<fixed<<setprecision(2);

classAverage = Average(num1, num2);
OutputAverage(fout, classAverage);

return 0;
}



double Average(int num1, int num2)
{
double classAverage;

classAverage = num1 / num2

return classAverage;
}

void OutputAverage(ofstream& fout, double classAverage)
{
fout<<"Class Average is: "<<classAverage;
fout<<endl;
}


the answer comes out as: 5.00 and it should be 5.57 or 5.58.
Last edited on
You have to cast in the expression:

lastYearAvg = static_cast<double>(num1)/num2;

Also, your Average function returns a garbage value (it returns the uninitialized classAverage variable - what's that even for?)
Topic archived. No new replies allowed.