Skip to content

Instantly share code, notes, and snippets.

@honorelsu
Created October 30, 2014 02:22
Show Gist options
  • Save honorelsu/8853e83afebad18bffe3 to your computer and use it in GitHub Desktop.
Save honorelsu/8853e83afebad18bffe3 to your computer and use it in GitHub Desktop.
C++ Functions Example
//Original equation from Homework #4
//double avg_hw=sum_homework_grades/count_homework_grades;
#include<iostream>
using namespace std;
//Average function
//The first line is the header
//You set the data type based on what this function will return
//In our case it will return an average, so its a double
//The variables in the parenthesis are the parameters we will pass to the function
//For our grader function we want the sum of the grades and then the count of grades
//Within the function we declare a variable called avg
//We use the equation from Homework #4 as the template and we divide the sum by the count
//We finish by returning the avg we calculate
double average(double sum, int count)
{
double avg;
avg = sum/count;
return avg;
}
//You can then call the function in main when you need to average something
int main ()
{
//I am hardcoding some numbers in so we can test
double a = 120.0;
int b = 3;
double score;
double score2;
//Here I call the average function
//Notice how I put a and b. If you look at the function it says double sum, and int count
//As long as the first paramter is a double and the second parameter is an integer
//You can pass any variables or numbers
score = average(a, b);
cout << "The average is " << score << endl;
//Here is an example with hardcoded numbers
//Notice the first parameter is a double and the second is an integer
score2 = average(100.0, 3);
cout << "The average is " << score2 << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment