HELP! How to use a loop to ask for 5 grades?
Feb 3, 2015 at 7:21pm UTC
I am only one week into programming, and I am wondering how I can turn the test scores into a for loop (instead of asking 5 times)?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
double project_1,test_1,test_2,test_3,test_4,test_5,overall_grade;
cout << "Please enter project_1 grade\n" ;
cin >> project_1;
cout << "Please enter test_1 grade\n" ;
cin >> test_1;
cout << "Please enter test_2 grade\n" ;
cin >> test_2;
cout << "Please enter test_3 grade\n" ;
cin >> test_3;
cout << "Please enter test_4 grade\n" ;
cin >> test_4;
cout << "Please enter test_5 grade\n" ;
cin >> test_5;
overall_grade = ((((test_1 + test_2 + test_3 + test_4 + test_5)/5)* 0.5) + (project_1 * 0.5))
cout << "Your grade is\n" ;
cout << overall_grade;
return 0;
}
Last edited on Feb 3, 2015 at 7:50pm UTC
Feb 3, 2015 at 7:50pm UTC
USe arrays and loops:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
int main ()
{
const int TESTS = 5;
double project;
double test[TESTS];
std::cout << "Please enter project_1 grade\n" ;
std::cin >> project;
double overall_grade = 0;
for (int i = 0; i < TESTS; ++i) {
std::cout << "Please enter test " << i + 1 << " grade\n" ;
std::cin >> test[i];
overall_grade += test[i];
}
overall_grade = overall_grade / 5 * 0.5 + project * 0.5;
std::cout << "Your grade is\n" << overall_grade;
}
Feb 4, 2015 at 12:32am UTC
Thanks for your help!
Last edited on Feb 4, 2015 at 12:52am UTC
Feb 4, 2015 at 12:50am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
const unsigned TESTS = 5;
double project;
double test[TESTS];
std::cout << "Please enter project_1 grade\n" ;
std::cin >> project;
double overall_grade = 0;
for (unsigned i = 0; i < TESTS; ++i) {
std::cout << "Please enter test " << i + 1 << " grade\n" ;
std::cin >> test[i];
overall_grade += test[i];
}
overall_grade = overall_grade / 5 * 0.5 + project * 0.5;
std::cout << "Your grade is\n" << overall_grade;
return 0;
}
You should used unsigned instead of int when it can/will never be negative.
You should always return 0 from main.
This compiles fine on GCC 4.8 and 4.9.
I'd also note that using
cin >> test[i]
is horrible as it won't handle any invalid input correctly. Look at using std::getline() and doing type conversions with stringstream or boost::lexical_cast<>()
Topic archived. No new replies allowed.