I am extremely confused. I have to follow these specific guidelines:
Make a program that will compute and output the average of 10 exam scores, entered by the user. Finish the function, so that the main will work correctly. Feel free to modify the main as you please as well.
I do not believe we need to change the main and do not believe we should use 10 variables. Here is the code I must add to, I believe the main is finished. Your help is very appreciated!!!!
#include <iostream>
using namespace std;
NOT ADD CODE HERE!!!
float calculateAverageTestScore(int amountOfScores);
int main(void)
{
const int NUMBER_OF_SCORES = 10;
cout << "The average test score was: " << calculateAverageTestScore(NUMBER_OF_SCORES) << endl;
return 0;
}
//INPUT: an amount of test scores
//OUTPUT: the average of these scores
//This function will obtain amountOfScores test scores from the user, and return
//their average - to be used elsewhere.
float calculateAverageTestScore(int amountOfScores)
{
float average;
//add code here
return average;
}
Should do the trick.
#include <iostream>
#include <string>
float calculateAverageTestScore(int amountOfScores);
int main() {
const int NUMBER_OF_SCORES = 10;
const float score = calculateAverageTestScore(NUMBER_OF_SCORES);
std::cout << "The average test score was: " << score << '\n';
}
float calculateAverageTestScore(int amountOfScores) {
float sum = 0;
std::string buffer;
for (int i = 0; i < amountOfScores; ++i) {
std::cout << "score #" << i + 1 << ": ";
std::getline(std::cin, buffer);
sum += std::stof(buffer); // TODO: Error handling
}
return sum / amountOfScores;
}
Related
I want to start off by saying I am brand new to C++. I have been learning off of websites and trying for hours shuffling around my code and trying new things in an attempt to solve this.
When I reference a variable while in the function where the variable is modified, it returns the correct value. Once that function is left, even though I've passed the variables on to the next function, the values get reset. I even went about adding couts here and there to display values to help me debug, but nothing was yielding any results. Can someone point me in the right direction please? I'll post my code below. Thanks for the help, guys.
#include <iostream>
//void Loop(int Total, int Spend);
//int NewTotal(int Total, int Spend);
//void Spent(int Total, int Spend);
void UserInput(int Total, int Spend);
// Loops back to UserInput() for next entry input
void Loop(int Total, int Spend)
{
UserInput(Total, Spend);
}
int NewTotal(int Total, int Spend)
{
std::cout << "Output of Total is: " << Total << std::endl;
std::cout << "Output of Spend is: " << Spend << std::endl;
return Total + Spend;
}
void Expense()
{
std::cout << "Please enter a description of your expense!" << std::endl;
char ExpenseDesc;
std::cin >> ExpenseDesc;
std::cout << "You described your expense as: " << std::endl;
std::cout << ExpenseDesc << std::endl;
}
void Spent(int Total, int Spend)
{
std::cout << "Please enter the amount you spent!" << std::endl;
std::cin >> Spend;
NewTotal(Total, Spend);
}
void UserInput(int Total, int Spend)
{
Expense();
Spent(Total, Spend);
std::cout << "Result of Total and Spend (NewTotal) is: " << Total + Spend << std::endl;
std::cout << "Record saved!" << std::endl;
std::cout << "So far, you have spent " << NewTotal(Total, Spend) << "!" << std::endl; //int Total & int Spend not retaining value when NewTotal(Total, Spend) gets called again to return value
std::cout << "Ready for next entry!" << std::endl;
Loop(Total, Spend);
}
int main()
{
int Total;
int Spend;
Spend = 0;
Total = 0;
UserInput(Total, Spend);
return 0;
}
Essentially, this is a very basic prompt that asks you for a description of a transaction (which only accepts one character, I need to fix that) and a transaction amount. Upon finishing that entry, you can make another one and the program is supposed to add the old total to the new total to arrive at a total spendings so far, and then repeat the prompt.
You need to either pass your variables by reference or return them from your functions. As it stands right now, you are creating copies of each variable that are local to each function, modifying the copies, and then discarding them at the end of scope.
Returning values:
std::pair<int, int> Spent(int Total, int Spend) {
...
return std::make_pair(Total, Spend);
}
// Getting values out
std::pair<int, int> result = Spent(Total, Spend);
int newTotal = result.first;
int newSpend = result.second;
// or
int newTotal, newSpend;
std::tie(newTotal, newSpend) = Spent(Total, Spend);
// or (C++17)
auto [newTotal, newSpend] = Spent(Total, Spend);
Reference parameters:
void Spent(int& Total, int& Spend) {
// Modifications to Total and Spend in this function will apply to the originals, not copies
...
}
Another option is to pass pointers:
void f(int* Total, int* Spent)
{
*Total = ...;
*Spent = ...;
}
Or use std::tuple:
std::tuple<int, int> f(int Total, int Spent)
{
...
return std::tuple<int, int>(Total, Spent);
}
I am in an introductory programming class and am having problems solving a problem. It would be greatly appreciated if anyone could help.
The program should display the average number of pounds of coffee ordered. The number of pounds ordered are stored in the pounds array. Complete the program using the while statement.
//Introductory22.cpp - displays the average number of pounds ordered
//Created/revised by <your name> on <current date>
#include <iostream>
#include <iomanip>
using namespace std;
//function prototype
double getAvg();
int main()
{
double pounds[6] = {10, 15.5, 17, 18.5, 11, 12.5};
double average = 0.0;
average = getAvg();
cout << fixed << setprecision(2);
cout << "Average number of pounds ordered: " << average << endl;
return 0;
} //end of main function
//*****function definitions*****
void getAvg()
{
int x = 0;
do // begin loop
{
cout << pounds[6] << endl;
x += 1 pounds[sub];
} while (x < 6);
return static_cast<double>(total) / numElements;
} //end of getAvg function
That is my code and I get error C4716 - getavg must return a value.
What simple way could I fix this?
Your function declaration and function definitions have different signatures. You need to change your definition to return a double.
I'm having a little trouble with my code. It's pretty much supposed to open two files, and compare the first twenty line of the file "StudentAnswers.txt" [inputted as a char into a char array] against a char value in (each line of another file) "CorrectAnswers.txt" in another array at the same position (index). It's like a linear search, but the same position in the arrays. Then a report should be displayed, detailing which question the student missed, the given answer, the correct answer, and if the student passed (got >= 70%) or not, like the following:
Report for Student X:
2 (A/D), 3 (C/D), 5(D/A)
This student passed the exam!
Then it should clear the SAArray, and feed the next twenty lines from StudentAnswers.txt, and start the process all over again. I guess the program has to determine the number of students from (lines of 'StudentAnswers.txt' file / 20).
I'm having trouble displaying the report, and having the array clear itself after the program. I'm guessing this can be done with a while loop and an accumulator for the number of students (to be determined by above equation).
Also, Visual Studio seems to go to "Missed __ questions for a total of ___ %", and then keep looping -858993460.
Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <array>
#include <algorithm>
using namespace std;
void GradeReturn(char[], char[], int, int, int);
string PassFail(float);
int main()
{
ifstream SA("StudentAnswers.txt");
ifstream CA("CorrectAnswers.txt");char CAArray[20];
char SAArray[20];
// char SA2Array[20];
bool isCorrect;
int correct;
int incorrect;
int counter;
correct = 0;incorrect = 0;
counter = 0;
cout << endl;
if (!SA.fail())
{
cout << "'StudentAnswers.txt' file opened successfully." << endl;
cout << "'CorrectAnswers.txt' file opened successfully." << endl << endl;
int a = 0;
int b = 0;
while (a < 20)
{
CA >> CAArray[a];
a++;
} // while loop to feed char into the array
while (b < 20)
{
SA >> SAArray[b];
b++;
}
} // while loop to feed char into array
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
return 0;
}
void GradeReturn(char CAArray[], char SAArray[], int correct, int incorrect, int counter)
{
float percent;
float hundred;
int student;
int catcher[20];
int writeCatcher; int starter;
int catcher_size;
student = 0;
writeCatcher = 0;
catcher_size = ((sizeof catcher) / 4);
while (counter < 20)
{
if ((CAArray[counter]) == (SAArray[counter]))
{
correct++;
cout << "Good job!" << endl;
} // correct handling
else
{
incorrect++;
cout << "You got question " << counter << " wrong." << endl;
counter >> catcher[writeCatcher];
writeCatcher++;
} // incorrect handling
counter++;
} // while loop to determine if a student got a question right or wrong
static_cast <float> (incorrect); // float conversion
cout << endl; // for cleanliness
percent = ((static_cast <float> (correct)) / 20); // percentage
hundred = percent * 100;
PassFail(percent);
if (PassFail(percent) == "pass")
{
student++;
cout << "Report for Student " << student << ":" << endl;
cout << "-----------------------------" << endl;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
starter = 0;
while (starter < (sizeof catcher)
{
if(1=1)
{
catcher_size
}
else
{
cout << "";
starter++;
}
}
}
else if (PassFail(percent) == "fail")
{
student++;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
while (starter < catcher_size)
{
if ((catcher[starter]) == -858993460)
{
starter++;
}
else
{
cout << "";
starter++;
}
}
}
return;
}
string PassFail(float percent)
{
if (percent >= 0.70) // if <pass>
{
return "pass";
}
else // if <fail>
{
return "fail";
}
cout << endl;
}
To get a loop you should keep streams open instead of closing them after reading 20 lines.
As pseudo code that would be:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
a = 0; // Reset a
}
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
You would also need to pass correct, incorrect, counter by reference so that the GradeReturn can change their value and their by do the accumulation.
Like:
void GradeReturn(char CAArray[], char SAArray[], int& correct, int& incorrect, int& counter)
Further you shouldn't rely on being able to read exactly Nx20 lines from the files every time. A file could have, e.g. 108 (5x20 + 8) lines, so you code should be able to handle the with only 8 lines. In other words, don't hard code 20 in your function like while (counter < 20). Instead pass the number of lines to be handled and do while (counter < number_to_handle).
Something like this as pseudo code:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
// ^
a = 0; // Reset a
}
}
if (a != 0)
{
// Process the rest
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
One problem you have is you're trying to compare C-style strings with the == operator. This will compare them essentially as if they were pointers to char, i.e. compare whether they point at the same location in memory, not compare the contents of the string. I urge you to look up array-decay and c-string variables to understand more.
Specifically, if (PassFail(percent) == "pass") isn't going to do what you want it to. strcomp doc, strncmp doc using std::string variables instead of c-style strings would all work, but it would be better simply to compare percent to a value, i.e. if(percent >= 0.70 directly instead of calling PassFail and comparing a string.
There are many other issues here also, you at one point call PassFail but do nothing with the return value. The only side affect of PassFail is cout << endl, if that's what you intend, it's a poor decision and hard to read way to put a newline on the console.
Try asking your compiler for more warnings, that's often helpful in finding these types of issues. -Wall -Wextra work for gcc, you may have to read your compiler manual...
I am working on a program that takes in grades from the user and returns the max, min, avg, median, and standard deviation. I keep encountering this error whenever I try to run my code:
File: c:\program files (x86)\microsoft visual studio 12.0\vc\include\vector
Line: 1201
Expression: Vector subscript out of range
Could someone tell me what I'm doing wrong? No matter what I do, I can't seem to fix it. Completely new to coding in C++, so if you could explain in-depth that would be extremely helpful.
This is the block of code it is referring to in the vector file:
#if _ITERATOR_DEBUG_LEVEL == 2
if (size() <= _Pos)
{ // report error
_DEBUG_ERROR("vector subscript out of range");
_SCL_SECURE_OUT_OF_RANGE;
}
Specifically pointing to this line:
_DEBUG_ERROR("vector subscript out of range");
My code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void enterGrades()
{
int count = 0;//initialize count
int grade;//initialize grade variable
int maxGrade = 0;
vector<int> gradeList;//initialize vector
vector<int>::iterator gradeListIt;//initialize iterator
do {
cout << "Enter grades [0 to exit]: ";//enter grades
cin >> grade;//user input
count += 1;//for each grade, increase count
gradeList.push_back(grade);//append grades to vector
} while (grade != 0);
};
int maxNum(vector<int> gradeList)
{
int largest = gradeList[0];//initialize largest number
int length = gradeList.size();
gradeList.resize(length);
for (int value = 0; value < length; value++)//traverse vector
{
if (gradeList[value] > largest)//if current value > largest
largest = gradeList[value];//set largest to that value
}
return largest;//return largest
};
int minNum(vector<int> gradeList)
{
int smallest = gradeList[0];
int length = gradeList.size();
gradeList.resize(length);
for (int value = 0; value < length; value++)
{
if (gradeList[value] < smallest)
smallest = gradeList[value];
}
return smallest;
};
int avgNum(vector<int> gradeList)
{
int total = 0;
int length = gradeList.size();
gradeList.resize(length);
for (int value = 0; value < length; value++)
{
total += value;
}
return total / length;
};
//int stdDev (vector<int>& gradeList)
//{
// int variance = 0;
// int avg = avgNum(vector<int>& gradeList);
// int length = gradeList.size();
// for(int value = 1; value < length; value++)
// {
// variance = variance + pow(value - avg, 2);
// }
// variance = pow(variance / length, 0.5);
// return variance;
//
//};
int main()
{
vector<int> gradeList;//initialize vector
vector<int>::iterator gradeListIt;//initialize iterator
enterGrades();//
cout << "Maximum grade is: " << maxNum(gradeList) << endl;
cout << "Minimum grade is: " << minNum(gradeList) << endl;
cout << "Average grade is: " << avgNum(gradeList) << endl;
}
Also, in my main function; can I call other functions like I did in my output statements?
Giving things the same name doesn't make them the same thing.
After enterGrades returns, the vector named "gradeList" in main is still empty.
When you try access the first element of an empty vector, you get an error.
Your main should look like this:
int main()
{
std::vector<int> gradeList = enterGrades();
cout << "Maximum grade is: " << maxNum(gradeList) << endl;
cout << "Minimum grade is: " << minNum(gradeList) << endl;
cout << "Average grade is: " << avgNum(gradeList) << endl;
}
Changing the implementation of enterGrades to fit is left as an exercise.
Also, this thing that you keep doing:
int length = gradeList.size();
gradeList.resize(length);
doesn't make sense, as it's resizing a vector to the size it already had.
Remove it.
You're also repeatedly declaring an iterator for no reason at all.
You also probably want to review what average you're supposed to calculate, as you're calculating the average index in a vector, not the average value.
And watch out for those integer divisions.
To clarify, this is a lab for class. I'm just learning all the fundamentals right now. I am trying to figure out how to print the total using a float variable AND a double variable (I thought we can just choose one or the other) while using loop mechanisms (while, do-while or for). I decided to go with the for loop. Any suggestions would be helpful. What I have now prints every single fraction until it gets to the very last one. I tried different variations but so far I got nothing.
I need help calculating the total for:
1/1 + 1/2 + 1/3 + 1/4 +....... 1/99999999 + 1/100000000
This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
float answer = 0;
int num;
for (int den = 1; den <= 100000000; ++den)
{
num = 1;
cout << num << "/" << den;
if (den == 100000000)
cout << " = " << endl;
else
cout << " + ";
answer += ( (float)num ) / ( (float)den );
}
cout << answer << endl;
}
Thanks!
At any point in time, your program has to be using either a float or a double, so I guess you're wanting to reuse your calculation code for each of those types in turn. Here's an example of how to do the calculation twice using a template - first for float, then for double:
#include <iostream>
template <typename T>
void calculate()
{
T answer = 0;
for (int den = 1; den <= 100000000; ++den)
answer += T(1) / T(den);
std::cout << answer << '\n';
}
int main()
{
calculate<float>();
calculate<double>();
}