Issue with division.

I am trying to create a program that calculates fraction of time remaining when a student leaves during the middle of the semester. I have to use function files here. I am having trouble with the division in function long double tuitionfrac(int, int, int).
No matter what numbers are entered, fractime gives an output of 0. I don't understand that.
1
2
3
4
5
6
7
8
9
10
 long double tuitionfrac(int opening, int leaving, int semend)
{
    int lefttime = semend - leaving;
    cout << "Left time " << lefttime << endl; //for error checking
    int tottime = semend - opening + 1;
    cout << "Total time " << tottime << endl;
    long double fractime = lefttime/tottime;
    cout << "fractional time " << fractime << endl; //always returns as 0.
    return fractime;
}
Integers can't hold fractions.

int / int --> int.

You need to explicitly convert at least one of the operands to a double first:

 
long double fractime = (long double)lefttime / totime;

Hope this helps.
lefftime and tottime are integers. When you divide them they're treated as such, and the division will get truncated to 0. You need to cast them to long doubles.

EDIT: Beat by Duoas
Last edited on
That seems to happen an awful lot to me... I'll post a response and be beat by a minute or less by someone else.
Thank you. That worked!
Topic archived. No new replies allowed.