Student here. I'm missing a single rubric item in the following project program and can't figure out where to place it, "it" being a pass-by-reference item. If anyone is feeling generous, please take a look at my program below and give me a heads-up about where I could tweak the code to make pass-by-reference possible. As it stands, I'm stumped and I don't have enough time to come up with an entirely new problem for which to code a solution. Thank you all in advance!
#include <iostream>
#include <cmath>
using namespace std;
//Global Variable
int height = 0;
//Function Prototypes
int getMale();
int getFemale();
int main()
{
//Local Variable
int ideal = 0;
char sex(' ');
//Sequence Structure
cout << "Welcome to the Hamwi Ideal Body Weight Equation Calculator!" << endl;
cout << "Please enter your height in inches (remember, 1 foot = 12 inches): " << endl;
cin >> height;
cout << "Please enter your biological sex (M or F): " << endl;
cin >> sex;
//Repetition Structure
while (toupper(sex) != 'M' && 'F')
{
cout << "Invalid entry. Please enter your biological sex (M or F): " << endl;
cin >> sex;
} //end while
//Selection Structure
if (toupper(sex) == 'M')
{
int ideal = getMale();
cout << "Thank you. Your ideal body weight is approximately: " << ideal << " pounds." << endl;
cout << "Have a nice day!" << endl;
} //end if
else
{
int ideal = getFemale();
cout << "Thank you. Your ideal body weight is approximately: " << ideal << " pounds." << endl;
cout << "Have a nice day!" << endl;
} //end else
return 0;
} //end of main function
//Program-Defined Function #1 (Male)
int getMale()
{
//Local Variable
int male = 0;
if (height >= 60)
{
male = 106 + ((height - 60) * 6);
return male;
} //end if
else
{
male = 106 - ((60 - height) * 6);
return male;
} //end else
} //end of male function
//Program-Defined Function #2 (Female)
int getFemale()
{
//Local Variable
int female = 0;
if (height >= 60)
{
female = 100 + ((height - 60) * 5);
return female;
} //end if
else
{
female = 100 - ((60 - height) * 5);
return female;
} //end else
} //end of female function
Declare your two functions like this
int getMale ( int& height );
int getFemale ( int& height );
And in your main you declare a variable that you can pass to the functions
int main()
{
// Declare here instead of globally
int height = 0;
// Then you can call
int result = getMale(height);
result = getFemale(height);
}
It will behave the same way. It is considered better practice to pass by reference than to use a global variable, so kudos to you for asking this question.
You pass height by reference in one of your gender functions.
For example:
int getMale(int &height) {
/* do stuff */
}
And then simply call it by:
getMale(height);
Also, are you required go use a global variable? If not, then make height a local variable in your main as other commenters have stated. Global variables are considered bad style, as they can cause hard-to-diagnose problems when you're working on a much larger project.
You could move variable height to main() (make it local) and pass it by reference to all your functions. Actually, I'd say that would be a better style than passing data through global variables.
But in a real project it's typically better to think of what behavior you want from your program, not of what awesome language features you want to use.
Is this program not giving you the correct answer and that's why you want to pass by reference? or what is the exact situation?
Anyways in order for you to pass by reference then you remove height from being a global variable and have it local in your main, then for your prototypes include a reference parameter then when you call them in main pass your local variable.
This is example of how pass by reference would work.
#include<iostream>
using namespace std;
//Prototype
void add(int num1, int num2, int &res);
int main()
{
int res;
add(1, 2, res);
cout<<"I got the value by passing my variable by reference"<<res<<endl;
return 0;
}
void add(int num1, int num2, int &res)
{
res = num1 + num2;
}
Related
Can someone give advice or guidance on what is wrong with my program? I do have the program fully written out, I am not sure where to add the function definition and function prototype to my program. This program involves pass by value and pass by reference. Also, any helpful notices on small errors will be appreciated
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Declare Variables
double amount = 22.66;
int num;
int dollars;
int quarters;
int dimes;
int nickels;
int pennies;
double x = 22.25;
double y = 55.55;
//Input
cout << "Please enter your dollar amount: ";
cin >> amount;
void showMenu() //function prototype
{
cout << "A. Money Exchange function" << endl;
cout << "B. Find Max Solution" << endl;
cout << "E. Exit" << endl;
cout <<"Please enter your choice:"<<endl;
}
void MoneyExchange(float amount, int& dollars, int& quarters, int& dimes,
int & nickels, int & pennies) // function prototype
{
int amount = 0, Remainder;
amount = amount * 100;
dollars = amount / 100;
Remainder = amount - (dollars * 100);
quarters = Remainder / 25;
Remainder = Remainder - (quarters * 25);
dimes = Remainder / 10;
Remainder = Remainder - (dimes * 10);
nickels = Remainder / 5;
Remainder = Remainder - (nickels * 5);
pennies = Remainder / 1;
}
double max(double x, double y) //function prototype
{
double max;
if (x >= y)
max = x;
else
max = y;
system("Pause");
return 0;
}
To use a function, you need to have a function method declaration (tell compiler/linker that this function exists) and implementation (stuff that function method does).
Here is a barebones example
void doStuff(); //im function declaration/prototype
void doMoreStuff(); //im function declaration/prototype
int main()
{
void doMoreStuff() //dont nest me in here!
{
cout << "doMoreStufff runs" << endl;
}
doStuff();
doMoreStuff();
return 1;
}
void doStuff() //im function implementation
{
cout << "doStuff runs" << endl;
}
Key take aways:
1) What you call a function prototype in your code is function implementation
2) No nesting implementation. for example: Dont do this
int main()
{
void doMoreStuff() //dont nest me in here!
{
cout << "doMoreStufff runs" << endl;
}
doStuff();
doMoreStuff();
return 1;
}
void doStuff() //im function implementation
{
cout << "doStuff runs" << endl;
}
(side note: one could nest anonymous/lambda functions inside)
3) In your case it doesnt matter if you stick method implementation above or below main{} implementation, just make sure you have your functions declared above main{} implementation (where these methods are used)
TLDR Poor naming conventions, not prototyping/declaring and defining properly, mismatched variable types, hiding value of amount (22.66, then cin, then int amount = 0 in MoneyExchange), unused code (max function), menu is not functional.
You are trying to define functions inside the main function like such:
int main() {
// ...
void showMenu() {
// code to do stuff
}
// ...
return 0;
}
It does not work like this. If you want to define and declare showMenu, so it can be used in main, try this. (See above)
void showMenu() {
// code to do stuff
}
int main() {
// ...
showMenu();
// ...
}
If you do not prototype the function, you must declare it above the main function. Otherwise it won't compile. (See above)
Try this (See below) if you want to prototype. You can have your prototypes in the main file or in a header file which you can include in main.
void showMenu(); // prototype
int main() {
// ...
showMenu();
// ...
}
void showMenu() {
// code to show the menu
}
If you want to define a function inside another, you should use a lambda expression.
Problems with your program:
-You define amount as a double of value 22.66 and then write over it when you cin >> amount. You only need to set the value once, so remove the cin or (preferably) change it to
double amount;
-Your functions and procedures, showMenu, MoneyExchange and max need to be moved outside of main, and prototyped or defined before main.
-You should find a naming convention which works for you and stick to it. You have procedure names starting with a capital MoneyExchange and then one starting with lower case, showMenu. Stick to the same, I'd use moneyExchange and showMenu.
You have done the same thing with variables, have a look here https://code.tutsplus.com/articles/9-confusing-naming-conventions-for-beginners--net-15584 this explains some naming conventions.
-Max function does not return anything. It must return a double, as you've declared. E.G.
double max(double x, double y) {
// ...
return 0.0;
}
-In MoneyExchange you declare a new int called amount, which you have declared locally in main as a double. You also set the value to 0, not the amount you inputted using cin.
-When you declare MoneyExchange, amount is taken as a float. So you pass a double, receive it as a float and then make a new int called amount... Stick to one data type. You also don't pass it by reference.
-You don't use the max function anywhere in this code.
-You don't get input from the menu, so the user does not have an option. I would use a switch statement. See this link http://www.cplusplus.com/forum/general/156582/ .
#include <iostream>
using namespace std;
// prototype functions
void DisplayResult(float MaxOrMin);
float FindMinimum(float Array[5]);
float FindMaximum(float Array[5]);
//Global Variables
float Array[5];
float MaxOrMin = 3;
float FindMin;
float FindMax;
//Main Function
int main()
{
cout << "Please enter 5 numbers: " << endl;
for (int i=0; i<5; i++)
{
cin >> Array[i]; // input for array
}
cout << "Please enter '0' for minimum or '9' for maximum:" << endl;
cin >> MaxOrMin; // input 0 or 9 for min or max
//Calling Functions
FindMinimum(Array);
FindMaximum(Array);
DisplayResult(MaxOrMin);
return 0;
}
//Function to find Minimum
float FindMinimum(float Array[5])
{
float FindMin = Array[0];
for (int y=1;y<5;y++)
{
if(Array[y] < FindMin)
FindMin = Array[y];
}
return FindMin;
}
//Function to find Maximum
float FindMaximum(float Array[5])
{
float FindMax = Array[0];
for (int x=1;x<5;x++)
{
if(Array[x] > FindMax)
FindMax = Array[x];
}
return FindMax;
}
This last part is my if, else if, else funtion:
//Function to display minimum or maximum result
void DisplayResult(float MaxOrMin)
{
if (MaxOrMin == 0)
cout << "Minimum is: " << FindMin << endl;
else if (MaxOrMin == 9)
cout << "Maximum is: " << FindMax << endl;
else
cout << "Invalid Input" << endl;
}
My project is to create a program using functions to take user input on a 5 float array. Then find the max and min and display whichever the user asks for.
Here is where my problem comes in. For both max(input 9) and min(input 0) I am getting "0". However any other input correctly returns my "Invalid Input" message.
I'm not getting any errors or warnings or errors at all on eclipse. My professor has told me that my problem was likely with my void function for displaying results. I am hoping someone could point me in the right direction here.
Apologies for my formatting and/or if this question is too basic for this site.
You misunderstand how local and global variables work. Your Find* functions shadow the globals with locals and thus they don't appear to do anything.
The problem is that your FindMinimum() (and the same with FindMaximum()) function compute the minimum (maximum) in a local variable and return it but you, in main() don't receive they in correct variables
So the computed value is lost.
I mean... instead of
FindMinimum(Array);
FindMaximum(Array);
you should write
FindMin = FindMinimum(Array);
FindMax = FindMaximum(Array);
I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();
So I'm trying to write a basic program in C++ to get the cost of something, the quantity, and calculate the total/subtotal, in three different functions, then display it in main().
Problem is, the variables aren't making it out of the function and I don't know why. I've put output statements inside the functions themselves to check, and the problem only seems to be when I'm trying to pull them out of said functions.
#include <iostream>
using namespace std;
int price(int cost)
{
cout << "What is the cost of the robot?" << endl;
cin >> cost;
if (cost < 1000) //validation
{
cout << "Cost is too low. Setting to $1000." << endl;
cost = 1000;
return cost;
}
return cost;
}
int numRobots(int number)
{
cout << "How many robots are being ordered?" << endl;
cin >> number;
if (number < 50) //validation
{
cout << "We only sell in quantities of 50 or more. Setting quantity to 50." << endl;
number = 50;
return number;
}
return number;
}
void grandTotal(int cost, int number, double &subtotal, double &total)
{
subtotal = (cost * number);
total = (subtotal * .07) + subtotal;
}
int main()
{
int cost = 0;
int number = 0;
double subtotal = 0;
double total = 0;
price(cost);`enter code here`
numRobots(number);
grandTotal(cost, number, subtotal, total);
cout << cost; //testing
cout << number; //outputs
cout << total; //of
cout << subtotal; //variables
system("pause");
return 0;
price(cost);
You are calling a function which returns an int, but you're not storing the int anywhere. You might want to go back to your text book and check the chapter on functions, and how they work. No offense but this is rather basic.
You're doing the same thing with numRobots.
Alternatively, you could pass the parameter by reference and modify it, but imo, that's less easy to understand.
tl;dr;
You should be doing int cost = price(); (there's no reason for the function to take an int as a parameter)
Use returned value or pass parameter by reference or pointer.
1.
int result = numRobots(number);
2.
int numRobots(int& number) {.....}
You need to pass the variables by reference:
int cost = 0;
int number = 0;
price(cost);
numRobots(number);
void price(int& cost)
{
....
}
void numRobots(int& number)
{
....
}
Note the void return type in this case!
Alternatively, you can utilize the return value:
int cost = price(cost);
int number = numRobots(number);
But this method doesn't make much sense because the variable passed as parameter to methods is the same as the one in which the return value is stored!
Im trying to lean structures and I think I am doing something wrong when I use the structure and trying to call it into a function.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//Structure
struct Inventory
{
int NumberPartsBin;
};
//Function Prototypes.
void choiceMenu();
void AddParts(int &);
void RemoveParts(int &);
int main()
{
char Election;
int choice;
Inventory Parts = {10};
const int Valve_Choice = 1,
Quit_Choice = 2;
I am trying to to resolve this problem with one item, but I will use arrays for 10 items.
do {
choiceMenu();
cin>> choice;
if (choice >= Valve_Choice & choice <= Quit_Choice)
{
switch(choice){
case Valve_Choice:
cout<<"Enter A for Add Parts or R to Romove Parts";
cin >> Election;
if (Election=='A')
{
AddParts(Parts);// My problem is here
}
if else (Election =='R'){
RemoveParts(Parts);}
else{
cout << "Invalid Entry. Try Again";
cin >> Election; }
break;
case Quit_Choice:
cout<<"Program Ending";
return;
else
{
cout<<"Enter a valid choice!!;
cin >> choice;
}
}
}
while (choice >= Valve_Choice & choice < Quit_Choice);
system("pause");
return 0;
// Bin Choice
void choiceMenu()
{
// We use ofstream to create and write on a text file.
ofstream outputFile;
outputFile.open("C:\\Users\\Alexander MR\\Desktop\\CompanyABCPayRoll.txt");
// The headed of the document.
outputFile << " Inventoy\n";
outputFile << " = = = = = = = = \n";
outputFile << " *Choose the part of your preference.\n";
outputFile << " 1. valves = " << Parts.NumberPartsBin << endl;
outputFile << " 11. Choose 2 to quit the Program" << endl;
outputFile.close();
}
I am not sure of my function either.
my function to add parts
void AddParts(int &Parts1)
{
int Enter1;
Parts1.NumberPartsBin = Parts1.NumberPartsBin + Enter1;
}
My function to remove parts
void RemoveParts(int &Parts2)
{
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
Reading the question with only parts of the code formatted is quite hard. The first thing I saw was:
void RemoveParts( int &Parts2 ) {
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
This makes no sense at all. If Parts2 is an int, then you will never be able to say Parts2.NumberPartsBin. The second thing is int Enter2;. You never give it a value, but in the next line you want to subtract it from something‽
I'm guessing (at least with this function) that you are trying to do something like this:
void RemoveParts( Inventory& inventoryItem, int amountOfParts ) { // inventoryItem is passed by reference, amountOfParts is passed by value
inventoryItem.NumberPartsBin = inventoryItem.NumberPartsBin - amountOfParts;
}
Looking at your code, I'm guessing you're quite new to all of this. I'm no guru, but please:
Capitalize class/struct names and start variable names with a lowercase. ( like parts or election)
If you want to change the value that comes into a function, pass it by reference, but if it is something like an int or a char, simply pass it by value.
p.s. it's if, else if, else and not if else which will otherwise be the next error in your code.