Osama Jutt
Osama Jutt

Reputation: 25

Variable percentage displaying zero value

Hey guys i have a bug that i am unable to detect. Kindly help me out. In this code i want to calculate a percentage but after the calculation there is a zero value store in the variable "percentage"

int _tmain(int argc, _TCHAR* argv[])
{
    int total_marks, obtained_marks, percentage;
    total_marks = 1100;
    cout << "enters yours obtained marks"<<endl;
    cin >> obtained_marks;
    percentage = (obtained_marks / total_marks) * 100;
    cout << "yours percentage =" << percentage;
    if (percentage >= 60)
    {
        cout << "you have passed with first division";
    }
    cout << "yours pecentage is=" << percentage;
    system("pause");
    return 0;
}

Upvotes: 0

Views: 648

Answers (2)

Andrew Henle
Andrew Henle

Reputation: 1

Integer division truncates towards zero.

Given

int total_marks, obtained_marks, percentage;

and

percentage = (obtained_marks / total_marks) * 100;

if obtained_marks is less than total_marks, the value of (obtained_marks / total_marks) will be zero. In that case,

percentage = (obtained_marks / total_marks) * 100;

will also be zero.

Even

percentage = (obtained_marks / total_marks) * 100.0;

will be zero, because the value in the parenthesis is still zero.

One better way would be:

percentage = ( 100 * obtained_marks ) / total_marks;

Upvotes: 2

nicomp
nicomp

Reputation: 4647

obtained marks and total marks are integers so you are getting zero when you divide. Change your data types to float or double.

Upvotes: 0

Related Questions