Below you will find my dismal attempt to create a user defined function. I am trying to do an assignment that calculates the area and cost of installing carpet for various shapes. I am also suppose to keep a running total of them. In addition the assignment requires that I use a used defined function. Right now all it does is accept the input of 1 and ask "What is the length of the side: ". It then loops back to the selection menu. It does not calculate a total much less keep track of the total. What am I doing wrong in creating the user defined function and how can I incorporate it to keep a running total till they exit?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void square(double);
const double UNIT_PRICE = 2.59;
const double LABOR_COST = 32.5;
const double PIE = 3.14;
const double TAX = .0825;
int main() {
int selection;
int sqrSide = 0;
// declare and initialize the variables for the shape
int sqrTot = 0;
do {
// get input from user as to what they want to do
cout << "Carpet Area Shape" << endl;
cout << "1. Square" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Circle" << endl;
cout << "4. Triangle" << endl;
cout << "5. Done" << endl;
cout << "Type a number to continue: ";
cin >> selection;
cout << endl;
// loop through the solutions based on the user's selection
switch (selection) {
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
case 2:
case 3:
case 4:
case 5: // exit
system("cls");
break;
default:
"You have made an invalid selection. Please choose a number from the "
"list.";
cout << endl;
}
// loop through if the user is still making a valid selection
} while (selection != 5);
system("pause");
return 0;
}
void square(double) {
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
// get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
When you declare the prototype of the function you can omit the parameter but in the implementation you must place it.
change:
void square(double)
{
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
to:
void square(double sqrSide)
{
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
and also change:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
to:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
system("pause");
break;
As mentioned by πάνταῥεῖ in a comment, it seems that you've a few misconceptions regarding scope of variables, about parameters and about return values. Let's see if we can't dispel some of those.
First of all, lets talk about scope. When we declare a variable inside a block delimited with { and }, the variable only exists inside that block. Code that follows the block cannot access the variable.
So, this is okay:
int a = 3;
int b = 2;
int c = a*b;
But, this is not, since the values of a and b are no longer available:
{
int a = 3;
int b = 2;
}
int c = a*b;
Next, lets talk about parameters. These are the inputs to functions which the function will use in order to complete its task. While their name is irrelevant and essentially meaningless, it will certainly help you and others of you give them meaningful names. Some programming languages and indeed, students of some disciplines don't follow this maxim and can produce code that's harder to follow than it need be. The implementation of Basic found in 20 year old Texas Instruments calculators and physicists, I'm looking at you!
Consider the following functions, (whose bodies I've ommitted for brevity):
double calcArea(double a)
{
...
}
double calcArea(double b)
{
...
}
They both suck. What's a stand for, how about b?
A far better pair might resemble:
double calcArea(double radius)
{
...
}
double calcArea(double sideLenOfSquare)
{
...
}
Lastly, lets talk about return values. In each of the 4 preceding functions, the declaration begins with double. This means that we can expect to get back a value of type double from the function. However, this is just coding - there's no magic and as such, we need to actually let the compiler know what this value will be. Extending the two previous functions, we might come up with some something like the following:
double calcArea(double radius)
{
return 3.1415926535 * (radius * radius);
}
double calcArea(double sideLenOfSquare)
{
return sideLenOfSquare * sideLenOfSquare;
}
Now as it turns out - even these two simple functions are not all they've cracked-up to be. Namely, the first function uses a constant - π (Pi or 3.141....) This already exists (and with far better precision than I've used) in the math.h header file. If this file is included, we then have access to the #defined constant, M_PI.
Next, both of these functions have the same name and take the same number of parameters of identical type. The compiler can't possibly know which one you'd like to invoke. At a minimum, they should have different names. Perhaps something like calcCircleArea and calcSquareArea. Now, the compiler knows which function you're referring to and will happily compile this part of the code. Errors may exist elsewhere, but these are a different matter.
A little research on function overloading will provide resources that can explain the problem and solution to functions with the same name far better than I am both able and inclined to try. :)
Related
I must write a program where the user can choose to practice with topic addition or topic multiplication that starts with a self-driven menu.
It must keep track of questions answered right, wrong and the number of questioned asked.
Which my current program is doing within each module(topic). Example Addition keeps track of the questions while the user is practicing Addition only and Multiplication does the same.
However, they are not being feedback to main, so they are not being added or displayed before the user can select another topic to practice or to exit the program.
Currently it is only to keeping track of the question (right /wrong/ total of questions) for each module (topic).
My goal is for the values to be passed to main and display the total number (right /wrong/ total of questions) before the user exits the program, but at the same time I must display the number of question in the Additional Topic and the Multiplication topic and provide a total.
Example Table of Addition, Multiplication and Totals ?
This is the code I have to start with. Can someone help me in how to code to return values of the (right /wrong/ total of questions) of the two topics and accomplish to display something like the table information.
******************************************************************************* /
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
// Implementing menu driven programs.
// Function Prototypes.
int menu();
void sums();
void products();
int main()
{
srand(time(0));
int option;
do {
option = menu();
switch (option) {
case 1: {
sums();
break;
}
case 2: {
products();
break;
}
default:
cout << "Program exit" << endl;
}
} while (option != 6);
return 0;
}
int menu()
{
cout << "Please select an option" << endl;
cout << "1) Practice with Addition " << endl;
cout << "2) Pratice with Multiplication " << endl;
cout << "3) Exit the program " << endl;
int option;
cin >> option;
return option;
}
void sums()
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValue = 10;
const int maxValue = 99;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << "What is " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
void products()
{
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValueOne = 0;
const int maxValueOne = 9;
const int minValueTwo = 10;
const int maxValueTwo = 99;
int y = (rand() % (maxValueOne - minValueOne + 1)) + minValueOne;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValueTwo - minValueTwo + 1)) + minValueTwo;
// cout<< " the random number is x "<< x << endl;
cout << " What is " << x << " x " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x * y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
}
I would create a structure that contains the number of total answers and number of correct answers—the incorrect ones can be inferred—and then pass a reference to an instance of the structure to the respective sums() and products() functions.
Those functions can then populate the structure elements and when they return, your main function can read them out, knowing exactly how many questions were asked, how many were answered, or whatever other information you want to record and retrieve.
I need help. I'm currently learning C++ programming and I'm still at the beginner level. I'm still figuring out how to make the while loop working. My idea is when inserting the correct code input, the switch statement choose the right case statement and loop back to insert another input until 0 inserted to stop the loop and calculate for the final output in main() constructor.
I know I have few kinks to fix soon but I'm still struggling to figure out this particular part.
#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
double sst = 0.06, total = 0, grandTotal, price, discount, newPrice, totalSST;
int quantity, count, code;
string name, ech;
void item001(){
name = "Rice (5kg)";
price = 11.5;
discount = 0;
}
void item002(){
name = "Rice (10kg)";
price = 25.9;
discount = 0;
}
void item003(){
name = "Sugar (1kg)";
price = 2.95;
discount = 0;
}
void item_cal(){
cout << "Please enter the quantity of the item: ";
cin >> quantity;
newPrice = (price + (discount * price)) * quantity;
cout << "\nItem: " << name << " || Quantity: " << quantity << " || Price: RM" << newPrice << endl;
}
void input(){
cout << "Welcome SA Mart\n" << "Please insert the code. Press 0 to stop: ";
while (code != 0){
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
}
}
}
int main(){
input();
totalSST = total * sst;
grandTotal = total + totalSST;
cout << fixed << setprecision(2);
cout << "Total: RM" << total << " ||SST: RM" << totalSST << " || Grand Total: RM" << grandTotal << endl;
return 0;
}
The only functional issue I see in your code is that there is a chance that the code variable will initialize to 0 (depends on the compiler/randomness). If that happens, your input method will return before it enters the loop. Other than that it looks like it will work. Of course, programming is not just the art of "making it work," style and readability are important too. In general, you want to confine variables to the smallest scope in which they are referenced. 'code' should not be a global variable, it should live in the input method. As for the loop, there are several ways it could be implemented: a "while(true)" loop could be used, in which case the variable may be defined inside the loop; on the other hand a "do while" would guarantee one loop runs (perhaps that would be a good fit here), but the variable must live outside of the loop, at least int the scope of conditional check. The way you choose is often a matter of style. Below, I use a "while(true)."
In programming, readability matters (a lot). I think this program would be easier to read if the data were broken up into a few structs, perhaps "Bill," and "Food." Another thing to consider is how to broaden the usage of your program, without introducing significant complexity. For example, it could work for any grocery store (any set of food items/prices). This is often a matter of determining an appropriate set of parameters to feed your program.
To do these things you might write something like this:
#pragma once
#include <string>
#include <map>
using namespace std;
namespace market {
const double& sst = 0.06;
struct Bill {
double total = 0;
double totalSST = 0;
double grandTotal = 0;
};
struct Food {
const char* name;
double price;
double discount;
Food(const char* name, double price, double discount = 0)
: name(name), price(price), discount(discount) {}
double result_price() const {
return price - price * discount;
}
};
struct GroceryStore {
const char* name;
std::map<int, Food> inventory;
GroceryStore(const char* name, std::map<int, Food> inventory)
: name(name), inventory(inventory) { }
};
void shop(const GroceryStore& store, Bill& bill, bool show_menu = false, int exit_code = 0) {
// check error conditions
if (store.inventory.find(exit_code) != store.inventory.end()) {
// that's the 'exit_code' code silly!
cout << "Bad store. Come back another time." << endl;
return;
}
cout << "Welcome to " << store.name << endl;
if (show_menu) {
cout << "The following items are available for purchase:" << endl;
for (auto p : store.inventory) {
cout << "\t" << p.first << ") " << p.second.name << "(" << p.second.result_price() << endl;
}
}
cout << "Enter the product code of the item you wish to purchase:";
int code;
cin >> code;
while (true) {
auto food_it = store.inventory.find(code);
if (food_it == store.inventory.end()) {
cout << "Thanks for stopping by." << endl;;
break;
}
cout << "Please enter the quantity of the item: ";
uint32_t quantity;
cin >> quantity;
auto& food = food_it->second;
auto disc_price = food.price - (food.discount * food.price);
bill.total += disc_price * quantity;
cout << "\nItem: " << food.name << " || Quantity: " << quantity << " || Price: RM" << disc_price << endl;
cout << "Would you like anything else? Enter the product code, or press " << exit_code << " to proceed to check-out." << endl;
cin >> code;
}
}
void ring_up(Bill& bill) {
bill.totalSST = bill.total * sst;
bill.grandTotal = bill.total + bill.totalSST;
}
void run() {
int code = 1;
GroceryStore store("SMart", {
{ code++, Food("Rice (5kg)", 11.5, 0) },
{ code++, Food("Rice (10kg)", 25.9) },
{ code, Food("Sugar (1kg)", 2.95, 0) }
});
Bill bill;
shop(store, bill, true);
ring_up(bill);
cout << "Total: RM" << bill.total << " ||SST: RM" << bill.totalSST << " || Grand Total: RM" << bill.grandTotal << endl;
}
}
Firstly there is a bug in input when u will input 0 then also it won't break while loop as code that is checked contains the previous value.
for example:
input is
3
0
but according to your code when the code will run the second time and while condition is checked code still contains 3 as value and code will run one more time
Try initialising code to some value, for example, -1. I'm not really sure but I think for global int variables, they initialise int variables to 0. So your first loop doesn't run. Or another way to do it is using do while loops instead of while loop.
do {
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
} while (code != 0);
}
This makes sure that the loop will run at least once, making code initialised.
Hope it helps you! Have fun programming!
How do I multiply a function to another function? and how do I properly use parameters?
I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.
Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.
For example:
float mealMath(numberOfAdults, mealChoosing){
//Rest of function
}
but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!
int numberOfAdults(){
int totalAdults;
cout << "Now how many adults will there be?: ";
cin >> totalAdults;
cout << "It seems there will be: " << totalAdults << " Adults." << endl;
while(totalAdults < 1){
cout << "Sorry there has to be a minimum of 1 adult!" << endl;
cout << "How many adults: ";
cin >> totalAdults;
}
return 0;
}
int numberOfKids(){
int totalKids;
cout << "Now how many Kids will there be?: ";
cin >> totalKids;
cout << "It seems there will be: " << totalKids << " kids." << endl;
while(totalKids < 0){
cout << "Sorry there has to be a minimum of 1 Kid!" << endl;
cout << "How many Kids: ";
cin >> totalKids;
}
return 0;
}
float mealChoosing(){
float cost;
string mealChoise;
cout << " " << endl;
cout << "Now, What meal will you be getting(D/S): ";
cin >> mealChoise;
if(mealChoise == "D"){
cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
cost = 25.95;
}
if(mealChoise == "S"){
cout << "It seems you have selected the Standard Meal plan for everyone!" << endl;
cost = 21.75;
}
cout << " " << endl;
return cost;
}
One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"
So I want numberOfAdults * mealChoosing but I want that done in a different function so
"float total(){
float totalBill;
totalBill = numberOfAdults * mealChoosing;
cout << totalBill;"
or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:
float mealMath(int a, float b){/*Your code here*/}
And then later call mealMath with the other two functions passed as arguments.
float x = mealMath(numberOfAdults(), mealChoosing());
Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.
It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.
Like mealChoosing() return totalAdults and totalKids (although its not needed here) from numberOfAdults(), numberOfKids() respectively.
int numberOfAdults() {
//...
return totalAdults;
}
int numberOfKids() {
//..
return totalKids;
}
float mealChoosing() {
//..
return cost;
}
Now on mealMath(numberOfAdults, mealChoosing)
float mealMathOutput = mealMath(numberOfAdults(), mealChoosing());
exercise prompt for code: Write a program that tells what coins to give for any amount of change from 1 cent to 99 cents. Use coin denominations of 25 cents (quarters), 10 cents (dimes), and 1 cent (pennies). Do not use nickel and half-dollar coins. Your program will use the following function (among others):
void compute_coins(int coin_value, int& num, int& amount_left);
#include <iostream>
#include <string>
using namespace std;
void prompt(int *amount_left);
void remaining_change(int *amount_left, int coin_value);
void compute_coins(int coin_value, int *num, int *amount_left);
void output(string coin_name, int *num);
int main() {
int change = 0, num = 0, amount_left = 0;
const int quarter = 25, dime = 10, penny = 1;
string q = "quarter(s)", d = "dime(s)", p = "penny(s)";
prompt(&change);
compute_coins(quarter, &num, &amount_left);
remaining_change(&amount_left, quarter);
output(q, &num);
compute_coins(dime, &num, &amount_left);
remaining_change(&amount_left, dime);
output(d, &num);
compute_coins(penny, &num, &amount_left);
output(p, &num);
}
void prompt(int *change)
{
cout << "How much change is there? ";
cin >> *change;
cout << "You entered " << change << endl;
cout << "That is equal to: ";
}
void remaining_change(int *amount_left, int coin_value)
{
*amount_left = (*amount_left % coin_value);
}
void compute_coins(int coin_value, int *num, int *amount_left)
{
*num = *amount_left / coin_value;
}
void output(string coin_name,int *num)
{
cout << num << " " << coin_name << ", ";
}
You are outputting the value of the pointers, not the value of the object pointed to.
The simple fix is to dereference the pointers first:
cout << "You entered " << *change << endl;
// ^
cout << *num << " " << coin_name << ", ";
// ^
However, I'd suggest not using pointers for things like this at all. For built-in types you should take a reference when you want to update the variable and a value otherwise.
Personally I wouldn't update those variables from inside the functions either, I'd carry out the necessary input or calculation and return a value to be assigned.
In prompt(), change is a pointer, so in order to output the value that change points to you would need to modify this line:
cout << "You entered " << change << endl;
to:
cout << "You entered " << *change << endl;
Better still, though, you could use a reference rather than a pointer:
void prompt(int &change)
{
cout << "How much change is there? ";
cin >> change;
cout << "You entered " << change << endl;
cout << "That is equal to: ";
}
and then you would just call this as:
prompt(change);
This is much more idiomatic C++ – the pointer method is more "old skool" C-style programming.
Ditto for the other places where you are printing the pointer itself, e.g. num.
I have a program that stores current a low numbers. The Object is to Store the low number every time time a new number is presented. so say I start the function the first number will equal the low number. but the trouble im having it once the function is called again it starts over and low is erased. Is there a way I can keep the function value once the function is called again? or does anyone know a better way of doing this while keeping function in a class?
Thanks
double a;
class rff{
public:
void FGH()
{
double b=0;
cout<< "pick a number"<<endl;
cin>>a;
b=a;
cout << "yournum";
cout << "LAST num:" << a<< endl;
cout << "Low num:" << b << endl;
cout <<"'pick another number"<<endl;
cin>>a;
if (a < b)
{
b = a;
}
cout << "yournum";
cout << "LAST num:" <<a<< endl;
cout << "Low num:" << b<< endl;
cin.get();
}
};
and source CPP
int main(){
rff ws;
ws.FGH();
ws.FGH();
ws.FGH();
cin.get();
cin.get();
return 0;
}
There is many mistakes in your code. Here I suggest something probably better (not tested, so you will maybe need to adapt it).
class MinimalChecker {
private:
double minValue;
public:
void MinimalChecker() {
minValue = std::numeric_limits<double>::max();
}
void check()
{
double userInput = 0;
cout << "Pick a number" << endl;
cin >> userInput;
if (userInput < minValue)
{
minValue = userInput;
}
cout << "Number typed:" << userInput << endl;
cout << "Lower number:" << minValue << endl;
cin.get();
}
};
Changes:
Better class/method names, easier to understand
No more global variable. Only a class member which store the minimal value starting when user has entered a number for t-he first time. It is initialized in the constructor with max value allowed by double type in c++.
Number is asked to user only one time. If you don't do that, each time you run your old FGH() function, the lower number is overriden without condition.