int samuelt1(){
ela = 80;
socials = 80;
total = ela + socials;
int grade = total / 11.5;
cout << "Samuel's grade average for term 1 is: " << grade << "%" << endl;
cout << "Individual Subjects: " << endl;
cout << "ELA: " << ela << endl;
cout << "Socials: " << socials << endl;
return grade;
}
int average(){
int avg = [samuelt1's grade??] / 1;
cout << avg;
return 0;
}
I'd like to pass the grade variable over to the average function; is there a way to do that? Thanks!
In the main function, store the value returned by the function samuelt1 in the variable Grade. Pass Grade as a parameter to the function average, like so
#include <iostream>
using namespace std;
int samuelt1(){
int ela = 80;
int socials = 80;
int total = ela + socials;
int grade = total / 11.5;
cout << "Samuel's grade average for term 1 is : " << grade << "%" << endl;
cout << "Individual Subjects : " << endl;
cout << "ELA : " << ela << endl;
cout << "Socials : " << socials << endl;
return grade;
}
int average(int grade){
int avg = grade / 1;
cout << "Average : " << avg;
return 0;
}
int main(){
int Grade = samuelt1();
average(Grade);
}
In C++, as in most languages, functions can be created to accept parameters and/or return values. To do this, you just need to specify a type and a name inside the parenthesis. Here is an example:
void printGrade(int grade)
{
cout << grade << endl;
}
int main()
{
int grade = 10;
printGrade(grade);
}
Running that program will print 10 to the screen. One thing to note is that when you pass in an integer parameter, the computer is just creating a copy of the value. This means the original grade variable is not changed or affected. Consider this example:
void printGrade(int grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You may expect this program to print 10, followed by 15. Since a copy of value is created inside the printGrade() function, the value of grade is affected only inside the scope of the printGrade() function. If you need to change the original value inside the printGrade() function, then you must pass the parameters by reference. Here is an example:
void printGrade(int &grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You'll notice in this example, the variable name is preceded with an ampersand. This tells the computer that you want to pass a reference to the grade variable to the function rather than making a copy.
Hopefully this all makes sense!
Related
at the moment I'm trying to add up the numbers for my hand and the hit cards, the issue is I created a function for my random number generator so that I can keep calling it into my dice game and the blackjack game, I would normally add the number generator to a variable and call it a day but I made it into a function instead. I am still new to c++.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void RandomNumber() { cout << (rand() % 10) + 1; }
void blackjack(int total) {
int startstakes = 15;
int stakes;
int hand;
cout << "Welcome to the Blackjack(21) table\n"
<< "How much are you adding to your initial 15 chip stake - ";
cin >> stakes;
cout << "New stake - " << stakes + 15 << " remaining chips - "
<< total - (stakes + 15) << endl;
cout << "Here is your hand - ";
RandomNumber();
cout << " and ";
RandomNumber();
cout << "Hit me cards: 0 - 0 - 0\n"
<< "Total = ";
system("pause>0");
}
int main() {
int total = 0;
int choice;
srand((unsigned)time(NULL));
cout << "Welcome to Royal Casino!!!, How much money do you wish to "
"convert? ";
cin >> total;
cout << "Excelent you currently have " << total << " Chips.\n"
<< "Let's Begin!\n\n"
<< "We have to tables available today\n";
cout << "1) Blackjack (21)\n"
<< "2) Dice\n"
<< "Both have an entry fee of 15 Chips\n"
<< "Select a table - ";
cin >> choice;
if (choice == 1) {
blackjack(total);
}
if (choice == 2) {
dice();
}
system("pause");
}
So the issue is that you should return the value instead of printing it. Like this (note the return type has changed from void to int)
int RandomNumber() {
return (rand() % 10) + 1;
}
A function which returns a value is much more flexible than a function which prints a value.
Now you can use a function call RandomNumber() pretty much the same way as a variable. E.g.
cout << RandomNumber() << " and " << RandomNumber();
or
int var = RandomNumber();
Hey so the code I made should be working to calculate the passer rating for quarterbacks in the NFL. The program, however, returns a value of 0 for almost anything, unless I put ridiculously large numbers, in which case it gives 100. What's wrong with it?
#include <iostream>
using namespace std;
int main()
{
int PassCompletions;
cout << "Enter pass completions" << endl;
cin >> PassCompletions;
int PassAttempts;
cout << "Enter pass attempts" << endl;
cin >> PassAttempts;
int TotalPassY;
cout << "Enter total yards" << endl;
cin >> TotalPassY;
int Touch;
cout << "Enter touchdowns" << endl;
cin >> Touch;
int Int;
cout << "Enter interceptions" << endl;
cin >> Int;
int C = (PassCompletions/PassAttempts-0.30)*5;
int Y = (TotalPassY/PassAttempts-3)*0.25;
int T = (Touch/PassAttempts)*20;
int I = 2.375 - (Int/PassAttempts*25);
if (C<0){
C=0;
}
if (Y<0){
Y=0;
}
if (T<0){
T=0;
}
if (I<0){
I=0;
}
if (C>2.375){
C=2.375;
}
if (Y>2.375){
Y=2.375;
}
if (T>2.375){
T=2.375;
}
if (I>2.375){
I=2.375;
}
int PasserRating = (C+Y+T+I)/6*100;
if (PasserRating <= 85){
cout << "Rating " << PasserRating << ", this is poor" << endl;
}
if (PasserRating > 85 && PasserRating < 90){
cout << "Rating " << PasserRating << ", this is mediocre" << endl;
}
if (PasserRating > 90 && PasserRating < 95){
cout << "Rating " << PasserRating << ", this is good" << endl;
}
if (PasserRating > 95){
cout << "Rating " << PasserRating << ", this is great" << endl;
}
You need use data type which is suitable to store fractional value. For this purpose use float instead of int for these statements:
float C = (PassCompletions/PassAttempts-0.30)*5;
float Y = (TotalPassY/PassAttempts-3)*0.25;
float T = (Touch/PassAttempts)*20;
float I = 2.375 - (Int/PassAttempts*25);
The variable type int is only used to store whole numbers, eg 1,2,3...
Any expression with a decimal will be truncated and rounded down. Since you are doing a lot of calculations with floating point numbers, eg. 2.375, I would suggest you changing your int's to float's
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my program ( I will include code below ), I have a function to determine the user's name and height. I use the name function first void name() and then the function void height() following it (of course main is last).
What I'm trying to do is to display the user's name throughout the program. In my second function, void height() Is ask the user how tall they are:
cout << " How tall are you?" << endl;
I would like to ask " How tall are you, name1?" , but the string name1 is not declared in the scope. Any ideas of how to make it work / what I'm doing wrong? Thank you. Also if you see any other issues or something I can do to make things easier/alternative ways, please let me know! (I'm new!)
#include <iostream>
#include <string>
using namespace std;
void name()
{
cout << "Welcome ________ ... uhmmmm, what was your name again? ";
string name1;
cin >> name1;
cout << " " << endl;
cout << " Oh that's right! Your name was " << name1 << ", how could I forget that?!" << endl;
}
void height()
{
//feet and inches to inches
cout << " How tall are you?" << name1 << endl;
cout << " " << endl;
cout << " " << endl;
cout << " Enter feet: ";
int feet;
cin >> feet;
cout << " " << endl;
cout << " Enter inches: ";
int inches;
cin >> inches;
int inchesheight;
inchesheight = (feet * 12) + inches;
cout << " " << endl;
cout << " Your height is equal to " << inchesheight << " inches total." << endl;
if (inchesheight < 65 )
{
cout << " You are shorter than the average male." << endl;
}
else if (inchesheight > 66 && inchesheight < 72)
{
cout << " You are of average height." << endl;
}
else
{
cout << " You are taller than average." << endl;
}
}
int main()
{
name();
height();
return 0;
}
Return a string instead of void.
string name()
{
cout << "Welcome ________ ... uhmmmm, what was your name again? ";
string name1;
cin >> name1;
cout << " " << endl;
cout << " Oh that's right! Your name was " << name1 << ", how could I forget that?!" << endl;
return name1;
}
Same thing with height(), for example, that should return an int. Also to get the name in your height function you could do.
int height(string name1)
{
// cout stuff about name
return userHeight;
}
Then you can call it like this:
int main()
{
string userName = name(); // takes the return from name and assigns to userName
int userHeight = height(userName); // passes that string into height()
return 0;
}
More examples of using functions and returning things:
int add(int a, int b)
{
int total = a + b; // the variable total only exists in here
return total;
}
int add4Numbers(int w, int x, int y, int z)
{
int firstTwo = add(w, x); // I am caling the add function
int secondTwo = add(y,z); // Calling it again, with different inputs
int allFour = add(firstTwo, secondTwo); // Calling it with new inputs
return allFour;
} // As soon as I leave this function, firstTwo, secondTwo, and allFour no longer exist
// but the answer allFour will be returned to whoever calls this function
int main()
{
int userA = 1;
int userB = 7;
int userC = 3;
int userD = 2;
int answer = add4Numbers( userA, userB, userC, userD ) // this grabs the value from allFour from inside the add4Numbers function and assigns it to my new variable answer
return answer; // now equals 13
}
Not a great title I know but I'm not sure how to word it. Anyway, in brief I am trying to calculate the number of scores, the total of scores and the average and grade of the scores. I am using for... loops to complete this task. So...
my function prototypes:
int validateNumber(int);
void summary(int,int,float,char);
char getGrade(float);
float getAvg(int,int);
probably only the validateNumber(int) is relevant here but just in case.
The main()
int num, total, scores;
cout << over4 << "How many scores do you want to average? " << endl;
cout << over4 << "Enter a value from 1 to 4: ";
cin >> num;
And the calls(?):
total = validateNumber(num);
summary(num,total,average,grade);
And then the definitions:
int validateNumber(int num)
{
int total = 0, score;
while (num < 1 || num > 4)
{
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++)
{
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100)
{
cout << over3 << score << " is not between 0 and 100! Renter the score: "
<< i << ": ";
cin >> score;
}
total += score;
}
return total;
}
and:
void summary(int num,int total,float average,char grade)
{
cout << over4 << "Number of scores : " << num << endl;
cout << over4 << "Scores total : " << total << endl;
cout << over4 << "Average : " << average << "%" << endl;
cout << over4 << "Grade : " << grade << endl;
cout << down11;
}
When the user enters a num value between 1 and 4, there is no problem, the program works as it should. However when the user enters a value for num not in that range, the function works as it should BUT the summary will tell me that the number of scores was that first erroneous value and as a result mess up my average/grade.
in your function you are passing by value not by reference, so the change which is done in your function int validateNumber(int); is only in that function's scope, outside num's value is same as it was first. you should send value by reference. in this way :
int validateNumber(int &);
What happens is that you pass num to the validateNumber function by value. The local num in the validateNumber function copies the global num's value and get's processed accordingly. However, the global num variable stays as it were. In order to change the num itself you will have to pass it by reference. Change the parameters on your function definition to: int validateNumber(int &num) { ... }
I'm having trouble with a homework assignment.
Everything works as expected except for the letter_grade part. I'm not getting any compile errors, but every time I run the program, the letter_grade is -858993460. I know it's probably something simple that I am overlooking, but I've hit a wall and am pretty much out of ideas.
#include <iostream>
#include <string>
using namespace std;
// Class Declaration
class StudentRecord
{
string id;
int A, B, C, D, F, grade;
float avg, exam1, exam2;
public:
void input();
void output();
void average();
void letter_grade();
};
// Gathering data
void StudentRecord::input()
{
cout << " Please enter your student ID: ";
cin >> id;
cout << "\n";
cout << " Enter your score for exam 1: ";
cin >> exam1;
cout << "\n";
cout << " Enter your score for exam 2: ";
cin >> exam2;
}
// Calculations
void StudentRecord::average()
{
avg = (exam1 + exam2) / 2;
}
void StudentRecord::letter_grade()
{
if ((avg >= 90) && (avg <= 100))
grade = A;
else if ((avg >= 80) && (avg < 90))
grade = B;
else if ((avg >= 70) && (avg < 80))
grade = C;
else if ((avg >= 60) && (avg < 70))
grade = D;
else (avg < 60);
grade = F;
}
// Output Data
void StudentRecord::output()
{
cout << "\n\n";
cout << " *** Student Record ***" << endl;
cout << "\n";
cout << " Student ID: " << id << endl;
cout << "\n";
cout << " Grade for exam 1: " << exam1 << endl;
cout << "\n";
cout << " Grade for exam 2: " << exam2 << endl;
cout << "\n";
cout << " Average for the class: " << avg << endl;
cout << "\n";
cout << " Letter grade for the class: " << grade << endl;
cout << "\n\n";
}
int main()
{
StudentRecord student;
student.input();
student.average();
student.letter_grade();
student.output();
system ("pause");
return 0;
}
You've declared integer variables named A, B, C, D, etc. That's not really what you want here. You want to declare grade as a char variable. You want to put the character 'A', 'B', etc. in that char variable.
Example:
grade = 'A';
That puts the character 'A' into the variable grade.
If you remove those variables A...F, change grade to be of type char, and then rewrite your if-else statement to assigned letters 'A', 'B', etc. to grade, that should do the trick.
Take note of those single quotes around the characters. Those tell C++ that the thing between the quotes is a character constant.
You are defining the "grade" values , A,B,C,D,F as integers. They are never initialized, so contain garbage in them. I think your intent was to print out a letter grade. In that case, you need to represent the values as strings, not numbers. Something like this:
char *A = "A";
char *B = "B";
etc.
The declaration of a variable is simply a label to identify a memory location ( simplified ). So, the name of the variable has no correlation to its value.