I am trying to make a function that has a int input parameter of a numerical grade and returns a letter grade with either a -, a +, or neither. I know how to do this without the use of reference parameters, but I am trying to use parameters and I am having some difficulty doing so.
One output parameter is the letter grade and the second output parameter is the + or - (+ if missed next grade by 1 or 2 points and - if just made the grade. Here is what I have:
#include <iostream>
using namespace std;
void letterGrade (int, float&, float&);
int main(){
int score;
float letter;
float sign;
cout << "Please input your grade (0-100): ";
cin >> score;
cout << endl;
if (score >=90 && score <=100){
letter == "Letter grade: A";
if (score == 90 ||
score == 91) {
sign = "-";
}
else if (score == 99 ||
score == 98) {
sign == "+";
}
else {
sign == " ";
}
}
letterGrade(score, letter, sign);
return 0;
}
If someone could point me in the right direction that still uses the parameters that would be very helpful. I think my main problem is I can't figure out how you make something = to a float within the if statement.
Thank you for any help or advise you might have!
You need to pass in the location at which the results will be stored.
So the minimal change to the current code would be to pass in an additional reference to a string that stores the results.
void letterGrade (int, float&, float&, std::string&);
Then when you call the function:
std::string results;//results are stored in here
letterGrade(score, letter, sign, results);//results are passed by reference here
Then in the letterGrade function you want to change whatever you were returning to be instead written to the results reference you passed in.
Additionally you are comparing floats with equality. Given that floats are not completely accurately stored in the computer this might end up not giving the behavior you wanted. If you compiled your code with all warnings enabled the compiler would have warned you about this. In future it's a good idea to compile with all warnings as you will quickly get feedback about potential issues. A quick way to fix your code would be to compare with less than and greater than operators. Read this for more info about the floats: https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf
Related
Precursor, I just started my first coding class, so forgive me if my mistake(s) is/are painfully obvious. All I need to do right now is use a programmer defined function to ask for an integer and read out an error message until the correct input is entered, then read out the correct input.
#include <iostream>
using namespace std;
bool evenint(int num1_par);//even integer declaration
int main ()
{
int num1, correctnum1;//even integer, function call variable
cout << "Enter an even integer between 2 and 12. \n";
cin >> num1;
correctnum1 = evenint(num1); //function call
cout << "You chose '" << correctnum1 << "'" <<endl;
return 0;
}
/*
Function: evenint
Parameter/Return: An even integer between 2 and 12 inclusively
Description: This function ensures the input matches parameters before
returning its value
*/
bool evenint(int num1_par)
{
if (!(num1_par>=2 && num1_par<=12 && num1_par % 2 ==0))// integer must be
between 2 and 12 inclusively
{
while (!(num1_par>=2 && num1_par<=12 && num1_par % 2 ==0))
{
cout << "Your number is invalid, please try again. \n";
cin >> num1_par;
}
return (num1_par);
}
else
{
return (num1_par);
}
}
I've tried switching my if-else/while loop to just a do-while/everything else I can think of but what I have now is the closest I've gotten. When I enter an invalid integer I get the correct response, but when I enter a valid integer it prints, "You chose '1'" no matter what valid integer I input. I've tried everything I know but now I'm stumped. Any help at all would be great!
Your function returns a bool which is either zero or one. Change it to int and your code will work.
my programming lecturer is teaching us how to write functions, terribly I might add, We are to make a program that calculates the grade of a students work. Here are the specs on it.
score 1 is weighted by 0.3,
score 2 is weighted by 0.5, and
score 3 is weighted by 0.2.
If the sum of the scores is greater than or equal to 85 then the Grade is an 'A'.
If the sum of the scores is greater than or equal to 75 then the Grade is a 'B'.
If the sum of the scores is greater than or equal to 65 then the Grade is a 'C'.
If the sum of the scores is greater than or equal to 50 then the Grade is a 'P'.
Otherwise the Grade is an 'F'.
So I wrote my code as follows:
#include <iostream>
using namespace std;
void calculateGrade() {
int score1, score2, score3;
int percentDec;
cin >>score1>>score2>>score3;
percentDec = (score1+score2+score3);
if (percentDec >= 85) {
cout << "The Course grade is: A";
}
else if (percentDec >= 75) {
cout << "The Course grade is: B";
}
else if (percentDec >= 65) {
cout <<"The Course grade is: C";
}
else if (percentDec >= 50) {
cout <<"The Course grade is: P";
}
else {
cout <<"The Course grade is: F";
}
} //end of calculateGrade()
int main() {
calculateGrade();
return 0;
}
Which works fine on my IDE but when I put it into the program which determines whether our answer is correct it doesn't work, that is because ordinarily we are asked only to put the stuff in main() but because it is a function and it's not in the main() it doesn't work like that. We are given this as an example and I'm about to throw something with how dumb this is. I don't know how to program it to work the way they want it.
cout << "The Course grade is: " << calculateGrade(90, 50, 99) << endl;
Cheers for any help.
This is not a forum for getting answers to your homework questions, although good job on showing what you have tried. Here are areas to look at:
1) The instructor is showing you that you can decompose code into functions. He/she wants you to wrtie a function calculateGrade that would work like this cout << "The Course grade is: " << calculateGrade(90, 50, 99) << endl;. Now every function declaration in C++ has three parts to it:
return_type functionName(param1_type param1, param2_type param2,...) {
// implementation
}
The functionName is what the function is referred to by (calculateGrade in this case), the parameters are the information you need to pass to the function for it to do its thing, and the return type is what the function will give back. In this case, your instructor is saying calculateGrade will take three integers as parameters and must return a string representing the grade of the student's scores. Thus your function should look like:
string calculateGrade(int score1, int score2, int score3) {
// ...
}
2) As the comments rightly pointed out, you aren't multiplying score1, score2, and score3 by their respective weights in the calculateGrade() method.
From your question and comments, I get the feeling your grasp of functions is not completely solid. Rather than complaining about your teacher (be it his/her fault or not), I suggest you read here about it. There are a plethora of online resources that will help you learn the basics of C++ programming.
You tutor is asking you to write a function which accept 3 parameter and return the grade.
char calculateGrade(int score1, int score2, int score3) {
char grade = 'F';
double percent = (0.3*score1 + 0.5*score2 + 0.2*score3);
if(...) {
grade = 'A/B/C/P'; // Depending upon condition, assign only value
}
else if(...) {
grade = 'A/B/C/P'; //Depending upon condition, assign only one value
}
// Add the condition in if else statements to get the actual grade.
return grade;
}
Note that the percent is of type double. You need to do all comparison in if else on double basis.
I am trying to write a program that requires input validation through functions. The idea behind it is much like the 21 stones only it is with 13 and the computer always wins. The game starts with 13 stones and the computer will always choose 1 on the first turn creating a multiple of 4 scenario. This means if the user takes 3 computer takes 1, user takes 2 computer takes 2 and so on until no stones remain. My problem is I am having a hard time getting my head around functions and how data is called from the parameters within so any help with this would be greatly appreciated!
This is what I have sofar.
#include <iostream>
using namespace std;
//function prototypes
bool validPick(int numStones);
int computerPick(int stones_in_pile, int player2taken);
int playerPick(int stones_in_pile);
int main()
{
int stones_left = 13, P1Taken, P2Taken;
cout << "You have shosen to play the game 13 stones against me, the MIGHTY "
<< "COMPUTER!\nThe object of the game is to take 1, 2 or 3 stones from"
<< " the pile on your turn.\nThe player that removes the last stone "
<< "or stones from the pile wins the game.\nGood Luck... You will need"
<< " it! I NEVER LOOSE!!"
<< endl << endl;
computerPick(stones_left, P2Taken);
playerPick(P1Taken);
validPick(stones_left);
//game logic here -- This is far from done.
stones_left -= P1Taken;
stones_left -= P2Taken;
return 0;
}
/******************************************************************************\
* Validate the picked number 1-3 are only valid numbers to choose from. *
\******************************************************************************/
bool validPick(int numStones)
{
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
/******************************************************************************\
* Computer's function calls. Should start with 1. We always want the computer *
* to win the game. *
\******************************************************************************/
int computerPick(int stones_in_pile, int player2taken)
{
if(player2taken == 0)
stones_in_pile -= 1;
else
{
if(player2taken == 1)
stones_in_pile -= 3;
else
if(player2taken == 2)
stones_in_pile -= 2;
else
stones_in_pile -=1;
}
return stones_in_pile;
}
/******************************************************************************\
* Player's Pick function call goes here. The player goes second *
\******************************************************************************/
int playerPick(int stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
Despite the fact that you should better read a beginners book than trying to understand C++ by asking such questions, I will try to explain what is wrong in your code by an example:
bool validPick(int numStones) {
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
This function is declared to return a bool value. However, if the condition in the if-clause turns out to be true, the function does not return anything, that is a mistake. Second, numStones is an int, so when you return it as a bool it will get converted (from int to bool) which is probably not what you want. Honestly, I didnt even try to understand the logic of your program but a valid version of this function could look like this:
bool validPick(int numStones) {
if((numStones < 1) || (numStones >3)) {
cout << "Invalid Selection. 1-3 is all you can have!";
return false;
}
return true;
}
There are many philosophies with functions that produce values and how those values are passed back.
Functions can pass values back to the caller by either modifying the parameter or by returning a value.
The playerPick function can either modify the passed value (by passing by reference):
void playerPick(int& stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
}
Or by returning a value:
int playerPick(void)
{
// Local variable to temporarily hold a value.
int stones_in_pile = - 1;
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
Note that the latter version uses a local, temporary, variable and the compiler will return a copy of the value upon end of the function.
I'm using void in the parameter for emphasis here.
I've been lurking around here for a long time, thank you for all your help in the past, even if this is the first question I've had to ask.
I'm trying to make a simple database program, and I am stuck the search requirement for it.
When searching, the user needs to be able to enter a question mark if they don't know a value. If you knew a movie was from the 90's you could enter 199? and it would find all the movies that matched 199_. I keep getting errors when I compile, "cannot convert 'char*' to 'char ()[5] for argument '2' to 'bool compareYears(const char, char (*)[5]"
I am trying to figure most of it out on my own, and I like to separate the functions and make them work in a separate .cpp file before adding them to the main file, just to make debugging easier.
#include <iostream>
#include <cstring>
#include <fstream>
#include <cctype>
using namespace std;
const int yearLength = 4;
typedef char year[yearLength + 1];
bool compareYears(const year year1, year year2[]);
int main()
{
year year1 = "1992"; //year from database, will be assigned the
// variable when implemented in main program.
year year2; //year entered by user, it will be compared to year1.
cout << "Enter a year to search for: ";
cin >> year2;
cout << endl;
if((compareYears(year1, year2)) == true)
cout << "they match\n";
if((compareYears(year1, year2)) == true)
cout << "they do not match\n";
return 0;
}
bool compareYears(const year year1, year year2[])
{
for(int i = 0; i < 4; i++)
{
if (strncom(year1, year2[i], 4) ==0)
return true;
else if (strncmp(year1, "????", 4) == 0)
return true;
else
return false;
}
}
Thanks for helping me out with this, usually the most help I get from others is useless or insulting. What I need help with most is getting rid of that compiler error. I cannot figure it out for the life of me.
First of all read this: typedef fixed length array
Then, use this typedef:
typedef struct year { char characters[4]; } year;
and change the code this way:
int main()
{
year year1;
year1.characters= "1992"; //year from database, will be assigned the variable when implemented in main program.
year year2; //year entered by user, it will be compared to year1.
cout << "Enter a year to search for: ";
cin >> year2.characters;
cout << endl;
if((compareYears(year1, year2)) == true)
cout << "they match\n";
else
cout << "they do not match\n";
return 0;
}
bool compareYears(year year1, year year2)
{
if (strncom(year1.characters, year2.characters, 4) ==0)
return true;
else if (strncmp(year1, "????", 4) == 0)
return true;
return false;
}
I also fixed some logical bugs
Just change these lines and it will work...the function declaration needs an array of year and you are trying to pass a variable..
if((compareYears(year1, &year2)) == true) //this changed from year2 to &year2
cout << "they match\n";
if((compareYears(year1, &year2)) == true) //this changed from year2 to &year2
cout << "they do not match\n";
The type of the year2 argument for compareYears looks strange. It looks like this argument is the mask to test against, i.e. a literal year like 1992 or something using wildcards. Hence, how about making it a char array of yearLength bytes?
It might be even easier to write just a generic function which is given two strings or arbitrary length (the second of which may use wildcards) and sees whether they are equal. The quality test could first see whether both strings are the same length and if so, whether the character at every position in both strings is either equal or the character at the given position in the second string is a '?'. You could use a single loop to walk over both strings in parallel to do this.
I have updated my calculator code, and am adding an exponent function. However, when I try to get the answer to the equation, i get this error:
(lldb)
Any help would be greatly appreciated, as This is my first day with C++!
Yep, that's all!
Here's my code!
#include <math.h>
#include <iostream>
int int1, int2, answer;
bool bValue(true);
std::string oper;
std::string cont;
using namespace std;
std::string typeOfMath;
int a;
int b;
int answerExponent;
int main(int argc, const char * argv[]){
// Taking user input, the first number of the calculator, the operator, and second number. Addition, Substraction, Multiplication, Division
cout<<"______________________________________________\n";
cout<<"|Welcome to The ExpCalc! Do you want to do |\n";
cout<<"|Exponent Math, or Basic Math(+, -, X, %) |\n";
cout<<"|Type in 'B' for basic Math, and'E' for |\n";
cout<<"|Exponential Math! Enjoy! (C) John L. Carveth|\n";
cout<<"|____________________________________________|\n";
cin>> typeOfMath;
if(typeOfMath == "Basic" ||
typeOfMath == "basic" ||
typeOfMath == "b" ||
typeOfMath =="B")
{
cout << "Hello! Please Type in your first integer!\n";
cin>> int1;
cout<<"Great! Now Enter your Operation: ex. *, /, +, -...\n";
cin>> oper;
cout<<"Now all we need is the last int!\n";
cin>> int2;
if (oper == "+") {
answer = int1 + int2;
}
if (oper == "-") {
answer = int1 - int2;
}if (oper == "*") {
answer = int1 * int2;
}if (oper == "/") {
answer = int1 / int2;
}
cout<<answer << "\n";
cout<<"Thanks for Using The ExpCalc!\n";
}else if(typeOfMath == "Exp" ||typeOfMath == "E" ||typeOfMath == "e" ||typeOfMath == "Exponent"){
cout<<"Enter the desired Base. Example: 2^3, where 2 is the base.\n";
cin>> a;
cout<<"Now what is the desired exponent/power of the base? Ex. 2^3 where 3 is the exponent!\n";
cin>>b;
answerExponent = (pow(a,b));
cout<< answerExponent;
} else(cout<<"Wrong String!");
}
Please help! I will probably ask a lot of questions aswell, so please dont get mad! I am also on a Mac, using Xcode 4!
Add this line to your includes:
#include <string>
With that done, I am able to get the code to compile and run with the correct output for 2^3, in both Visual Studio, and in GCC 4.7.2 using ideone.com (click here to see the output). However, my compiler still emits a warning because of a conversion from double to int which you should probably attend to by casting. Change this:
answerExponent = (pow(a,b));
To this:
answerExponent = static_cast<int>(pow(a,b));
With that said, the compiler is emitting that warning for a reason, and by casting you are basically just telling the compiler to "shut up and do it anyway". A better approach is to avoid the need for a cast. Instead of doing the above change, change this line:
int answerExponent;
To this:
double answerExponent;
This makes more sense, because there is little point in calling pow with doubles as arguments if you are going to throw away the fractional part of the number afterwards.