Help on LAB 3.3 answer keep coming 0 " Working with String Input and Type Casting"

// Lab 3 percentage.cpp
// This program will determine the percentage
// of answers a student got correct on a test.
// PUT YOUR NAME HERE.

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
string firstName,
lastName;
int numQuestions,
numCorrect,
totalPoints;
double percentage;

// Get student's test data
cout << "Enter student's first name: ";
cin >> firstName;
cout << "Enter student's last name: ";
cin >> lastName;

// WRITE A STATEMENT TO READ THE WHOLE NAME INTO THE name VARIABLE.

cout << "\nNumber of questions on the test: ";

cin >> numQuestions;


cout << "\nNumber of answers the student got correct: ";

cin >> numCorrect;

// Compute and display the student's % correct
totalPoints = ( numCorrect/numQuestions);
percentage = (totalPoints * 100);

// WRITE A STATEMENT TO COMPUTE THE % AND ASSIGN THE RESULT TO percentage.
cout << "\n" << lastName << "," << firstName << " received a score of " << percentage << " on this test.\n";
// WRITE STATEMENTS TO DISPLAY THE STUDENT'S NAME AND THEIR TEST
// PERCENTAGE WITH ONE DECIMAL POINT.

return 0;
}

Last edited on
 
totalPoints = ( numCorrect/numQuestions);

This is doing integer division as both numCorrect and numQuestions are integers. Hence the result will also be an integer.

Also the variable totalPoints is an integer too, and any floating-point value stored in it would be truncated to an integer result.

You could do it this way:
 
    double totalPoints = (double) numCorrect /numQuestions;
Here the (double) in parentheses before the variable numCorrect is a c-style cast.

You can read about type casting here:
http://www.cplusplus.com/doc/tutorial/typecasting/

Or alternatively you could do it without the need for a cast:
 
    percentage = 100.0 * numCorrect / numQuestions;

Here the value 100.0 is of type double. As long as at least one of the values in multiply/divide is a double, then the other value is promoted to a double before the expression is evaluated. But beware of order of operations. If you did it like this, it would still be incorrect:
 
    percentage =  (numCorrect / numQuestions) * 100.0;
as an integer divide is done before the multiply.
Last edited on
Topic archived. No new replies allowed.