I'm trying to the program to display the bonus, but the programs renders an answer to 0. I am extremely new to c++ so any guidance would be greatly appreciated.
Here's the code:
#include <iostream>
#include <iomanip>
using namespace std;
//function prototypes
void enterItems(double, double);
void calcAndDisplayBonus(double &salesAmt, double &rate);
int main()
{
//declare variables
double sales = 0.0;
double bonusRate = 0.0;
//enter input values
enterItems(sales, bonusRate);
//calculate and display bonus
cout << fixed << setprecision(2);
calcAndDisplayBonus(sales, bonusRate);
system("pause");
return 0;
} //end of main function
//*****function definitions*****
void enterItems(double salesAmt, double rate)
{
cout << "Enter sales: ";
cin >> salesAmt;
cout << "Enter bonus rate (in decimal form): ";
cin >> rate;
} //end of enterItems function
void calcAndDisplayBonus(double &salesAmt, double &rate)
{
cout << "Bonus: $" << salesAmt * rate << endl;
} //end of calcAndDisplayBonus function
When you call enterItems, you are passing parameters by copy. This means that your changes won't affect the variables available in the scope of the caller.
To solve it, you can either pass a couple of references or pointers, as well as rely on a pair returned from the function as a result, and so on.
As an example, by writing:
void enterItems(double &salesAmt, double &rate)
You'll actually solve the problem above mentioned.
Another valid prototype is:
void enterItems(double *salesAmt, double *rate)
Even though this one asks for a small set of changes all around your code (the example, of course).
There is a plenty of possible solutions, hoping these ones will give you an idea of what's wrong.
Your function
void enterItems(double salesAmt, double rate)
is taking two double-parameters by value, this means, your changes you do inside the function will not be visible from the outside. You could take the doubles by reference:
void enterItems(double &salesAmt, double &rate)
but i'd prefer to return the values, but since you can only return a single value you'd need two functions:
double enterSales()
{
double tmp;
cout << "Enter sales: ";
cin >> tmp;
return tmp;
}
double enterBonus()
{
double tmp;
cout << "Enter bonus rate (in decimal form): ";
cin >> tmp;
return tmp;
}
//in your main:
double sales = enterSales();
double bonusRate = enterBonus();
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/ .
For my C++ program, I need to use 3 functions to ask user to input mass, accleration, and displacement, calculate force and work with those inputs in a diff function, then output force and work in the 3rd function.
My problem is that Im having trouble passing the values for mass, accleration, and displacement from the first function to the 2nd so that I can calculate force and work..Here's my code so far
using namespace std;
string userName;
int amounts(float, float, float); //function prototype
int calcForceAndWork(float, float); //function prototype
;
int main()
{
float mass, accleration, displacement;
string userName;
cout << "Hello user, what is your name?" << endl;
cin >> userName;
amounts(mass, accleration, displacement);
cout << "Enter the mass value: " << endl;
cin >> mass;
cout << "Enter the displacement value: " << endl;
cin >> displacement;
cout << "Enter the accleration value: " << endl;
cin >> accleration;
return 0;
}
int calcForceAndWork(float, float)
{
amounts(mass, accleration, displacement);
calcForceAndWork(force, work);
double force, work;
force = mass*accleration;
work = force*displacement;
return 0;
}
These are my first 2 functions. How do I pass the values of mass, accleration, and force from my first function to the 2nd function?
I'm afraid you need to learn about the absolute raw basics of functions, return values, passing by value vs passing by reference, etc. still...
Let's keep it really simple. Just use "pass by value", and return a result. Here's an example:
int getSum( int a, int b )
{
return a + b;
}
int main()
{
int myValue1 = 1, myValue2 = 2;
int mySum = getSum( myValue1, myValue2 );
return 0; //this is returned to the OS. 0 == no error, i.e. success
}
Function main calls function getSum. It passes the values stored in the variables called myValue1 and myValue2 to that function. Function getSum receives those values into variables called a and b. It adds them together and returns the value. That return value is stored in the mySum variable in function main. If you wanted, you could then pass that mySum value on to another function.
At the end of function main, it returns 0. That is a "special" return. main is the entry point function for the operating system into your program. By convention, you return 0 to the OS to indicate success. Any other number returned to the OS is considered an "error code".
My formatting is really bad, and I'm sorry for that, but I'm still in the very early stages of learning C++. Anyway, no matter what I try, I always get an expected unqualified ID error on line 51. Any assistance would be greatly appreciated! And no, the code is not finished, its due March 20th, just wanted to start on it early. And this is NOT how I wanted to format it, but this is how it was stated on the rubric. I'm brand new to functions, so yeah, any help would be awesome!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu (int); //Menu prototype for 4 options
int main()
{
const int numWidth = 4;
int choice, pick;
cout << "Welcome! Please select your choice by entering 1, 2, 3, or 4!" << endl;
cout << "1:";
cout << right << setw(numWidth) << " Enter the Grades" << endl;
cout << "2:";
cout << right << setw(numWidth) << " Display the Grades" << endl;
cout << "3:";
cout << right << setw(numWidth) << " Show overall Grade" << endl;
cout << "4:";
cout << right << setw(numWidth) << " Exit the program" << endl;
cout << "Select your choice and press enter ";
cin >> choice;
pick = menu(choice);
cout << pick;
if (choice ==1)
{
cout << ". Please enter your grades.\n";
}
float AssignmentGrade(float, float, float, float); // Assignment Grade Prototype
{
float asgnment1, asgnment2, asgnment3, asgnment4, total;
cout << "First, enter your 4 assignment grades ";
cin >> asgnment1 >> asgnment2 >> asgnment3 >> asgnment4;
total = AssignmentGrade (asgnment1, asgnment2, asgnment3, asgnment4);
cout << total;
return 0;
}
}
float AssignmentGrade (float num1, float num2, float num3, float num4)
{
float asgnmentgrade;
asgnmentgrade = num1*0.05 + num2*0.05 + num3*0.05 + num4*0.05;
cout << "Total points, including weights, for assignment grade is ";
return asgnmentgrade;
}
float LabTestGrade (float, float, float); // Right here, line 51, is where I get expected unqualified ID error before {
{
float lab1, lab2, lab3, total;
cout <<"Next, please enter your 3 lab test scores!";
cin >> lab1 >> lab2 >> lab3;
total = LabTestGrade (lab1, lab2, lab3);
cout << total;
return 0;
}
float LabTestGrade (float lab1, float lab2, float lab3)
{
float LabGrade;
LabGrade = lab1*0.10 + lab2*0.10 + lab3*0.10;
cout << "Total points earned from lab tests is";
return LabGrade;
}
int menu (int num)
{
int option;
option = num;
cout <<"You have selected ";
return option;
}
Delete unnecessary ; in your 51st line: float LabTestGrade (float, float, float);
Dont forget that ; is used for the end of a command. If you define a function, you don't use it. Look at th following model:
float function (float parameter) {
command();
command();
return 0;
}
Edit: There's the same syntax error in your 31th line.
Delete ; again in float AssignmentGrade(float, float, float, float);
You will find yourself running into a few other problems with this function, apart from the original unqualified ID that #Nichar answered.
At Line 50 you have:
float LabTestGrade (float, float, float) { // Function Code }
and at Line 60 you have:
float LabTestGrade (float lab1, float lab2, float lab3) { // Function Code }
This will cause a compile error as you are trying to define another function with the exact same name and parameters. (Redefinition error)
Although these functions may look slightly different as you have named the parameters of the second one (float lab1, float lab2, float lab3), to the compiler it will simply see two functions that are named the same and take in the same types as parameters.
That being said, you can delete the parameters in the first LabTestGrade() as they aren't actually being used inside its function.
float LabTestGrade() { // Function Code }
Finally, you are also going to want to swap around the order that these two functions are being defined. I suggest googling C++ Scope but basically the first LabTestGrade() is making a call to the second LabTestGrade(float lab1, lab2, lab3) like so.
total = LabTestGrade(lab1,lab2,lab3);
However, the second LabTestGrade hasn't been defined yet within your program so it will try to call the first LabTestGrade() again and give you an error because the first LabTestGrade() doesn't take in any parameters now and this line of code is trying to pass into it three floats into a function that takes in nothing.
Alternatively, you could just declare the functions above your main function like you had done for your menu function.
float LabTestGrade();
float LabTestGrade(float lab1, float lab2, float lab3);
int menu(int) // Menu prototype for 4 options
Hi even im a beginner but heres what i think -
First of all
The menu prototype in the beginning is incorrect . Prototypes should be exactly same as the function itself .
Correct prototype will be
int menu (int num);
In line 51 , in the parameter bracket, try writing the full name of the float types you r trying to get. Also remove the semicolon. Ex:-
float LabTestGrade (float a , float b , float c) { }
A similar mistake is made in the AssignmentGrade function which takes 4 floats.
Try writing the full name as parameters. Remove the semi colon.
Write the function prototypes separately in the beginning outside the main.
You have to create a separate prototype for every function you make and remember - prototypes should have the same name as the function. Just you need to replace the curly braces with a semi colon.
Hope this helps.
EDIT:- You can also try writing the functions outside main and then use prototypes in the beginning outside the main.
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!
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ passing variables in from one Function to the Next.
The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of paint.
//Problems with this not working
void showMenu();
void getUserData(int &, double &, int &);
void doEstimate(int &, double &, int &, double &, double &);
void showReport();
int main()
{
int choice;
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this int calc ect
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get the user's choice.
showMenu();
cin >> choice;
// Validate the menu selection.
while (choice < 1 || choice > 2)
{
cout << "Please enter 1 or 2: ";
cin >> choice;
}
if (choice == 1)
{
//for some reason it just keeps repeating the function getUserData
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
showReport();
}
} while (choice != 2);
return 0;
}
void getUserData(int &rooms, double &costOfPaint, int &totalsqrtfeet)
{
int sqrtfeet;
int count = 0;
cout << "Please enter the number of rooms to be painted: ";
cin >> rooms;
cout << "Please enter square feet of wall space in each room: ";
cin >> sqrtfeet;
for (count = 1; count <= rooms; count++)
{
cout << "Please eneter square feet of wall space in room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet;
}
cout << "What is the cost of the paint: ";
cin >> costOfPaint;
system("cls");
system("pause");
}
void doEstimate(int &calcGallonsOfPaint, double &calcCostOfPaint, int &calcHoursOfLabor, double &calcLaborCost, double &calcPaintJobCost)
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this: puting int rooms ect
int rooms, totalsqrtfeet;
double costOfPaint;
getUserData(rooms, costOfPaint, totalsqrtfeet);
calcGallonsOfPaint = 1 * (totalsqrtfeet/110); //Calculates the number of whole gallons of paint required.
calcCostOfPaint = calcGallonsOfPaint * costOfPaint; //Calculates the cost of the paint required.
calcHoursOfLabor = calcGallonsOfPaint * 6; //Calculates the number of whole hours of labor required.
calcLaborCost = calcHoursOfLabor * 15.00; //Calculates the labor charges.
//Calculates the cost of the paint job. This is the sum of the labor charges and the cost of the paint required.
calcPaintJobCost = calcLaborCost + calcCostOfPaint;
/*110 square feet of wall space
one gallon of paint
six hours of labor
$15.00 per hour for labor
*/
}
void showReport()
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
cout << "The number of rooms to be painted: " << rooms << endl;
cout << "The number of whole gallons of paint required: " << calcGallonsOfPaint << endl;
cout << "The hours of labor required: " << calcHoursOfLabor << endl;
cout << "The cost of the paint: " << calcCostOfPaint << endl;
cout << "The labor charges: " << calcLaborCost << endl;
cout << "The total cost of the paint job: " << calcPaintJobCost << endl;
system("pause");
system("cls");
}
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-)
On top of that, you call getUserData from your main function and then again from doEstimate. And then you call them both again in showReport. That's why it's asking four times. Just call getUserData once. Since it's homework, I'll leave you to figure out where but here's a hint. If you do it in main (nudge, nudge, wink, wink), you'll have to pass he variables into doEstimate as well, not create new variables of the same name within that function and magically expect the compiler to associate them with the originals.
To caveat on what paxdiablo said, you are calling getUserData in your nested while loop, but I don't understand the purpose of calling getUserData(rooms, costOfPaint, totalsqrtfeet); prior to doEstimate(...) when the data isn't used nor passed to doEstimate(...) until you call getUserData again while inside the doEstimate(...) function. You should pass by value the rooms, costOfPaint, and totalsqrtfeet variables to doEstimate(...) or make them global since you only have one main() function anyways. If you had some sort of OO solution, then I wouldn't recommend making them global and rather part of a class.
Also all these variables are ZERO or NULL when they are passed into doEstimate(...):
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost
If you want to output them, then you need to pass them by reference to doEstimate(...) and then when it gets to the cout then it will sufficiently print the correct values. That is why it is zero.
The bottom line is though you need one function to call the other functions. That would be the simplest plan at this point, such as:
GetDataAndPrint(...) {
// Get some data
// Do estimate, pass in values by reference
// Print Results from calculated values
// return
}