Functions With Parameters Full Source Code

Aug 10, 2013 at 4:12pm
I have a sample code project that I would like to offer the community for their use. Full source provided. (Teaching what I've learned helps me learn).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "stdafx.h"
#include <iostream>

using namespace std;

//our custom function with two parameters (float x and float y);
float myFunc(float x, float y){

	//multiplies the parameters;
	float answer = x*y;
	//returns and stores the answer for later use in our main function;
	return answer;
	
	}

//the main function;
int main ()
{
	//declare floats;
	float a, b;
	//user prompt;
	cout << "Enter two numbers to multiply \n";
	//user input;
	cin >> a;
	cin >> b;
	//print the returned value;
	cout << myFunc(a, b) << "\n";
	//pause the computer system;
	cin.get();
	
}
Last edited on Aug 11, 2013 at 4:14pm
Aug 10, 2013 at 4:19pm
This expression statement

//function with user inputted parameters;
myFunc(a, b);
//print the returned value;
cout << myFunc(a, b) << "\n";

is superfluous and should be removed.
Aug 10, 2013 at 5:22pm
What if I put the output (cout) in the function itself?
Last edited on Aug 10, 2013 at 5:27pm
Aug 10, 2013 at 5:28pm
I see what you were saying now, you're right. Thanks.
Aug 10, 2013 at 6:27pm
Just to elaborate what vlad is saying, your function returns a value, so simply calling it was pointless as the value was returned, then lost. Using cout, you print that value.
Aug 10, 2013 at 11:48pm
How would you change it?
Aug 10, 2013 at 11:52pm
What are you going to change?
Aug 11, 2013 at 5:46am
You can use a variable to store the function.
1
2
3
 float X;
X = myFunct(a,b);
cout << X <<"\n";
Last edited on Aug 11, 2013 at 5:47am
Aug 11, 2013 at 8:03am
@jkevin: the variable stores the value returned by the function, not the function itself.

@Micronomics: I assume you know why system("PAUSE"); is bad - if not, some Google searches will clear it up. I have the correct way memorized.
Last edited on Aug 11, 2013 at 8:03am
Aug 11, 2013 at 4:07pm
Yes, I don't like the system pause method, but I needed the console open long enough for me to see it. Usually, in a longer program, I will just return the entire script to the main function.
Aug 11, 2013 at 4:09pm
jKevin, that is a much cleaner way of doing things.

I am usually under the impression that the end user doesn't see my code and therefore, never mattered.

But these methods are much more productive.
Aug 11, 2013 at 4:10pm
I have a search algorithm I completed last month, do you guys want to review the source? The user enters a search item, and it displays the result as well as the index location of its array.
Aug 11, 2013 at 4:15pm
Wow, that system pause method is ridiculously expensive. I changed it to cin.get();
Topic archived. No new replies allowed.