Osama Jutt Osama Jutt - 11 days ago 5
C++ Question

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;
}

Answer

Integer division truncates towards zero.

Given

int total_marks, obtained_marks, percentage;

and

percentage = (obtained_marks / total_marks) * 100;

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);

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.

One better way would be:

percentage = ( 100 * obtained_marks ) / total_marks;