Why is my code not outputting (just) numbers? - c++

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.

Related

How to code in C++ mutiple return values to main from mutiple modules and display each modules totals?

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 keep getting a variable uninitialized error when calling a function that is asking for user input

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.

How to call user defined functions in C++?

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. :)

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

Currency Conversion Program

I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);