Hi, I'm having trouble with the int lab() part, specifically at the end, when I put in my calculations. What I'm trying to find is the average points of whatever the user inputs in lab().
For example, when I run the program and input in 7 for labs, and 4 for points, I get back 40, however when I try to set that equation into an int variable, I get 10, or sometimes a really large number.
Can anyone explain to me why that is and what is wrong with my code?
#include <iostream>
usingnamespace std;
int lab () {
int labs, point_value, how_many, points, r;
r = (points*labs)/labs*10;
cout << "How many labs?" << endl;
cin >> labs;
cout << "Do the point values vary? Enter 0 for no, 1 for yes" << endl;
cin >> point_value;
if (point_value == 0){
cout << "Enter lab points: " << endl;
cin >> points;
cout << (points*labs)/labs*10 << endl;
cout << r << endl;
return r;
}
}
int main () {
int calculate_what, l;
cout << "What would you like to calculate an average for?" << endl;
cin >> calculate_what;
if (calculate_what == 1) {
l = lab();
cout << "Your average is: " << l << endl;
}
return 0;
}
For example, when I run the program and input in 7 for labs, and 4 for points, I get back 40, however when I try to set that equation into an int variable, I get 10.
And your code is : r = (points*labs)/labs*10;
My impression is that when you enter 7 labs and 4 points, then r = (4 * 7) / 7 * 10 = 28 / 70 = 0.4 not 40.
You should let r become a double so that it can store floating-point values.
Also, the code above should be changed to : r = (points*labs) / static_cast<double>(labs * 10);
Or : r = (points*labs) / double(labs * 10);
Integer divided by another integer will always result in an integer not a double.
My impression is that when you enter 7 labs and 4 points, then r = (4 * 7) / 7 * 10 = 28 / 70 = 0.4 not 40.
I think it follows the PEMDAS order of operations, so I believe it would do (4*7) first, then 28 / 7, and then finally 4*10 which would all equal to 40.
What if point_value is not zero? What value do you want to return?
Probably something like:
1 2 3 4 5 6 7
elseif (point_value == 1){
while (labs > 0) {
cout << "Enter amount of points" << endl;
cin >> points;
p += points;
cout << p << endl;
labs--;
and another else statement that loops the code if the user enters something other than 1 or 2.
In addition to TheIdeasMan's post, you input only labs but not points.
1 2 3 4 5 6 7
cout << "How many labs?" << endl;
cin >> labs;
cout << "How many points?" << endl;
cin >> points;
r = (points*labs)/labs*10; // This line should be here