Reputation: 31
I started college this year doing a course in software development. I've just started doing loops in c++ and have been assigned a number of questions to solve. I have the code done for the first question but part of the output is not working correctly and I can't figure out why.
The problem is to read in the marks of 10 student in a test and then output the pecentage of student that received an honors mark (over 70)
Here is my code
int _tmain(int argc, _TCHAR* argv[])
{
int grade;
int numfirstclass = 0;
int percentfirstclass;
for (int count = 0; count < 10; count++)// For loop to run 10 times to allow 10 grades to be entered
{
cout << "Enter your grade ";
cin >> grade;
if (grade >= 70)
numfirstclass++;
}
cout << "The number of students with a first class honours degree is:" << numfirstclass;
percentfirstclass = (numfirstclass / 10) * 100;
cout << endl << "The Percentage of students that recieved a first class degree is: " << percentfirstclass;
return 0;
}
My problem is that the output for percentfirstclass is always 0 and I can't figure out why.
Any explanation would be appreciated
I'm using visual studio 2013
Upvotes: 0
Views: 123
Reputation:
Just give the type double
.Write
double percentfirstclass;
percentfirstclass = (numfirstclass / 10.0) * 100;
instead
int percentfirstclass;
percentfirstclass = (numfirstclass / 10) * 100;
Upvotes: 0
Reputation: 20244
Use
percentfirstclass = (numfirstclass / 10(double)) * 100;
numfirstclass / 10
will always evaluate to 0 (except when numfirstclass
is 1) as it is an integer division and multiplying 100 and 0 is always 0.
Using the cast will make numfirstclass / 10(double)
result in a number having a decimal part and then,it will be multiplied with 100 . This number will then be assigned to percentfirstclass
and as percentfirstclass
is an int
,the decimal part will be truncated.
Upvotes: 1
Reputation: 36
As cool guy told change the percentfirstclass to float or double, in your above code you are trying to divide an integer by 10 which is lesser than 10, so the program returns 0 as output i.e.
int c =1; int d = c/10;//gives 0 because integers cannit support decimals
if you use
float d = c/10;//you will get your required output
Hope you got it.
Upvotes: 0
Reputation: 311126
The problem is that subexpression
(numfirstclass / 10)
of expression
percentfirstclass = (numfirstclass / 10) * 100;
is always equal to 0 because numfirstclass
is always less than 10 except one case when numfirstclass is equal to 10.:) There is used the integer arithmetic.
You could either define numfirstclass
as having type float (or double) or rewrite the statement as
percentfirstclass = (numfirstclass * 100 ) / 10;
or to force the expression to be evaluated as a float number
percentfirstclass = (numfirstclass / 10.0) * 100;
Upvotes: 1