How do I get this code to work? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Struggling with this, can't seem to get it to work. Here is what I need to do:
1.Ask the user how many weeks were in the landscaping season this year.
2.Dynamically create an array of double floating point data that can be used to store the sales for each week of the season.
3.Using a for loop, have the user enter in the sales data for the season.
4.Pass the array (and its size) into a function that will display all the sales for the weeks in a nice table.
5.Call another function that will take in the array as an argument and will total the sales for the season (returning the total to the main function).
6.Have the program tell the user the total sales for the season and the average sales per week.
7.After this delete the allocated memory and set the pointer to 0.
Any assistance helps always I don't quite understand functions, or pointers. and I've read about both a lot!!
#include <iostream>
#include <iomanip>
using namespace std;
int Weeks = 0;
double total;
double sales;
void SalesTable(int);
double Total (int, double[]);
double average;
int main()
{
double Season[Weeks];
cout << "How many weeks were in the landscaping season this year: ";
cin >> Weeks;
for (int i = 1; i<Weeks+1; i++)
{
cout << "Enter sales data for week " << i <<": ";
cin >> sales;
}
Season[Weeks]=sales;
SalesTable(Weeks);
Total(Weeks, Season);
average = total/Weeks;
cout << "The total sales for the season are: "<<setprecision(2)<<showpoint<<fixed<<total<< endl;
cout << "The average weekly sales were: "<<setprecision(2)<<showpoint<<fixed<<average;
return 0;
}
void SalesTable(int Weeks)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << sales <<endl;
}
}
double Total(int Weeks, double Season[])
{
for(int i = 1; i<Weeks+1; i++)
{
total += Season[Weeks];
}
return total;
}

Ok , using pointer to double it will do what you need :
int Weeks = 0;
double total;
double sales;
void SalesTable(int, double*);
double Total (int, double*);
double average;
int main ()
{
double *Season;
cout << "How many weeks were in the landscaping season this year: ";
cin >> Weeks;
Season = new double [ Weeks ];
for (int i = 1; i<Weeks+1; i++)
{
cout << "Enter sales data for week " << i <<": ";
cin >> sales;
Season[i-1]=sales;
}
SalesTable(Weeks, Season);
Total(Weeks, Season);
average = total/(double)Weeks;
cout << "The total sales for the season are: "<<showpoint<<fixed<<total<<endl;
cout << "The average weekly sales were: "<<showpoint<<fixed<<average;
delete[] Season;
return 0;
}
void SalesTable(int Weeks,double *Season)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << Season[i-1]<<endl;
}
}
double Total(int Weeks, double *Season)
{
for(int i = 1; i<Weeks+1; i++)
{
total += Season[i-1];
}
return total;
}

Since I can't comment yet, I'll post a new answer:
The code provided by T-D still doesn't work because of this: the print out for each sales week is always the same because it isn't accessing the elements inside of the Seasons array.
void SalesTable(int Weeks)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << Season[i - 1] << endl;
}
}
Also, to dynamically create an array which allows the user to control the size of the array at runtime use the following code:
double *season = new double[Weeks];
And because you dynamically created the array, you have to manually release its resources:
delete[] season;

Related

Calculations wont display in output

I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}

C++ program on how much a person would earn over time if salary is one penny per day (Not an IT student)

I have a project to write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
This is my code so far and I can't seem to get it to work properly (not an
IT student)
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
int days;
double pennies = 0.01;
double total = 0.0;
double fixed;
double showpoint;
cout << "For how many days will the pay double?";
cin >> days;
cout << endl << "Day Total Pay\n";
cout << "------------------------\n";
for (int count = 1; count <= days; count++)
{
cout << count << "\t\t$\t" << (pow(2, pennies)) << endl;
}
cout << setprecision(2) << fixed << showpoint;
cout << "--------------------------------\n";
cout << "Total $\t" << total << endl;
getch();
return 0;
}
I've tried to explain the changes I have made, but if you need to know more please ask
// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
int days = 0;
// double pennies = 0.01; Not needed.
double total = 0.0;
// If you don't initialise variables it will cause a crash or undefined behaviour.
// double fixed;
// double showpoint;
while (days < 1) // This prevents negative or 0 day contracts.
{
// You need to use the full name to cout or that abomination of a command using namespace std
std::cout << "For how many days will the pay double?";
std::cin >> days;
}
std::cout << std::endl << "Day Total Pay\n";
std::cout << "------------------------\n";
// looping from 0 while less than days is more "normal".
for (int count = 0; count < days; count++)
{
double payForTheDay = (pow(2, count));
std::cout << count << "\t\t$\t" << payForTheDay << std::endl;
total += payForTheDay; // You need to increment the total.
}
// Not sure what this is about
// std::cout << std::setprecision(2) << fixed << showpoint;
std::cout << "--------------------------------\n";
std::cout << "Total $\t" << total << std::endl;
getch();
return 0;
}
Try to replace (pow(2, pennies)) with (pennies * pow(2, (count - 1)))...
Notes:
Shouldn't pennies actually be named dollars?
To calculate the total, just increase it by the daily salary for each day (e.g. inside the loop where you output each table row).
So look at the basic of the problem. It is basically a geometric progression.
In a geometric progression sum of n numbers is;
Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]
Use the formula to get number of pennies for n days.
Now convert it into dollar value.
If you need full code comment here.
Quite late, but using bitwise shift is the best thing for 2^n in my opinion. It's fast and easy to use.
int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
// Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
cout<<"Day "<<K<<": "<<(1<<K)<<"\n;
Here 1<<K is 2^K
Alternatively, you can use a variable to save the payment
and shift it by 1 each iteration.

C++ Arrays in a Beginner Application

I need to write a program that allows the user to enter 12 double values representing store sales for each month of one year. After all 12 values are entered, I need to display each month’s sales amount and a message indicating whether it is higher, lower, or equal to the average month’s sales amount. I can get the program to list the month by number and average the sales, but I am unable to get it to list the months by NAME and as well as compare each month to the average and display whether it is higher, lower, or equal to the average amount. I've looked through the forums here and at cplusplus.com but am not getting anywhere. I'm not looking for finished code, but any advice is appreciated. My code:
#include"stdafx.h"
#include<iostream>
using namespace std;
int main()
{
const int MONTHLY_SALES = 12;
const char month[12] = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'};
double totalSales = 0;
double storeSales[12];
double AVERAGE;
int x;
for(x = 0; x < MONTHLY_SALES; ++x)
{
cout << "Enter the sales for month #" << (x + 1) << " ";
cin >> storeSales[x];
}
cout << endl << "The sales for each month are:" << endl;
for(x = 0; x < MONTHLY_SALES; ++x)
{
totalSales += storeSales[x];
cout << storeSales[x] << " ";
}
cout << endl;
AVERAGE = totalSales / MONTHLY_SALES;
cout << "The average sales is " << AVERAGE << endl;
return 0;
}
Thanks for any and all help!
Firstly, your compiler should not have let you get away with that definition of month. You need to declare the array as const char* and use double quotes, since these are strings:
const char *month[12] = {"Jan", "Feb", ... , "Dec" };
You can then get the month name using month[x] where x is an integer between 0 and 11.
As for the averages, something simple like this in another loop:
int diff = storeSales[x] - AVERAGE;
if( diff < 0.0 ) {
// below average
} else if( diff > 0.0 ) {
// above average
} else {
// equal
}
Bear in mind also that you are dealing with double values, so in some cases an average that appears to be the same value (rounded) as something else might in fact be above or below.

Sorting both a string array and a double array from highest to lowest(parallel arrays) and aligning the text

Alright I'll bite, this program does sort the number from highest to lowest but it'll only sort if the numbers are arranged in order from highest to lowest;not if it's sporadic. Here are two example of what I mean.
Example 1: 12,11,10,9,8,7,6,5,4,3,2,1.
Example 2: 32,25,24,31,10,11,15,16,8,19,18,5.
You see how in example 2 that some of the numbers are in order like 32 25 24 but some of the others are not. This is my main problem. My secondary problem is aligning the text vertically so that it looks neat. Should I use setw left, right for this? Please give feedback.
Note 1: The IDE that I'm using is codeblocks.
Note 2: Keep in mind that whatever number the user inputs for a particular month has to be vertically parallel to each.
Note 3: I'm pretty sure the problem is with my selection sort. So you really should be looking at the function void selectionsort since that is the function that is doing all the sorting. I just don't know where I went wrong with my sorting though. Everything else seems to be in order.
/* This program lets the user enter the total rainfall
for each month into an array of doubles. The program also
calculates and displays the total rainfall for a year, the average
monthly rainfall, and the months with the highest and lowest amounts.
The program also displays the list of months, sorted in order of
rainfall from highest to lowest.*/
/* This program does not accept negative numbers for monthly rainfall
figures.*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void SelectionSort(string[], double[], int);// Function Protoype.
int main()
{
const int SIZE = 12; /* A constant integer that represent the total
amount of months in a year. */
double totalRainfallPerMonth[SIZE]; /* Loop this array to force the user
to enter variables for each
element in this array. */
double totalRainfallPerYear = 0; /* The total amount of rainfall
(in inches) per year. */
// An array of every month.
string monthArray[SIZE]={"January", "February", "March", "April", "May",
"June", "July","August", "September",
"October", "November", "December"};
double average; // A variable that holds the average monthly rainfall.
int i; // Will be used as a counter for any loop.
cout << fixed << showpoint << setprecision(2); // Set decimal notation.
for(i=0; i<=11; i++)
{
// Prompt the user to enter values.
cout << "Please enter the total rainfall(in inches) for ";
cout << monthArray[i] << ": ";
cin >> totalRainfallPerMonth[i];
while(totalRainfallPerMonth[i] < 0) /* If the user enters a negative
value */
{
cerr << "No negative values allowed. "; // Display error message.
cout << "Please try again. ";
cin >> totalRainfallPerMonth[i];
}
}
for(i=0; i<=11; i++)
{
// Calculate the total rainfall for a year.
totalRainfallPerYear += totalRainfallPerMonth[i];
}
// Display the total rainfall for a year.
cout << "\nThe total rainfall this year is " << totalRainfallPerYear;
cout << " inches of rain. " << endl;
// Calculate the average monthly rainfall.
average = totalRainfallPerYear / SIZE;
// Display the average
cout << "\nThe average monthly rainfall per month is ";
cout << average;
cout << " inches of rain. " << endl << endl << endl;
cout << "\n" << "Month " << "\t";
cout << " Rainfall(in inches)" << endl;
cout << "-----------------------------------";
SelectionSort(monthArray, totalRainfallPerMonth, SIZE); /* Call in the
function. */
return 0;
}
void SelectionSort(string month[], double rain[], int SIZE)
{
int i;
int j;
int min;
for (i = 0; i < SIZE - 1; i++)
{
min = i; // The intial subscript or the first element.
for (j = i + 1; j < SIZE; j++)
{
if (rain[j] > rain[min]) /* if this element is greater,
then it is the new minimum */
{
min = j;
// swap both variables at the same times
double tempDouble = rain[i];
rain[i] = rain[j];
rain[j] = tempDouble;
string tempString = month[i];
month[i] = month[j];
month[j] = tempString;
}
}
}
for(i=0; i<=11; i++)
{
/* Display the amount of rainfall per month from highest to
lowest */
cout << "\n" << month[i] << "\t" << rain[i] << endl;
}
}
There is in fact an error in your selection sort implementation: you are swapping elements too early and too often.
Only after you have performed a full sweep over the whole remaining array and therefore have determined the global minimum (I keep that term in order to be consistent with the variable name and the comments in the code, although in fact you are looking for the maximum) you should perform a single swap of the first element of the remaining array with the minimum element.
The corrected code (only the main loop of the sorting function shown) should look like this:
for (i = 0; i < SIZE - 1; i++)
{
min = i; // The intial subscript or the first element.
for (j = i + 1; j < SIZE; j++)
{
if (rain[j] > rain[min]) /* if this element is greater,
then it is the new minimum */
{
min = j;
}
}
// swap both variables at the same times
double tempDouble = rain[i];
rain[i] = rain[min];
rain[min] = tempDouble;
string tempString = month[i];
month[i] = month[min];
month[min] = tempString;
}

I need help with classes. (C++)

Well I am trying to do an exercise in my programming book and it's difficult for me to grasp exactly what it wants.
My "enterAccountData()" function is suppose to ask the user for an account number and a balance neither of which can be negative and the account number cannot be less than 1000
The second one is the one I am stuck on "computeInterest()" THis function is suppose to accept an integer argument that represents the number of years the account will earn interest. The function then displays the account number from the previous function and displays its ending balance at the end of each year based on the interest rate attached to the BankAccount class. (The interest rate on "BankAccount" has to be a constant static field which is set at 3 percent(0.03)).
So My question is this: How do I set up "computeInterest()" too allow it to calculate the interest using the constant static field when my debugger will not allow me to actually keep the field as a constant? I am not trying to stop any random errors from happening for now, just trying to get the jist of what the book is exactly asking for. Here is my code.
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
static double annualIntRate;
public:
void enterAccountData(int, double);
void computeInterest();
void displayAccount();
};
//implementation section:
double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
cout << setprecision(2) << fixed;
accountNum = number;
accountBal = balance;
cout << "Enter the account number " << endl;
cin >> number;
while(number < 0 || number < 999)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> number;
}
cout << "Enter the account balance " << endl;
cin >> balance;
while(balance < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> balance;
}
return;
}
void BankAccount::computeInterest()
{
const int MONTHS_IN_YEAR = 12;
int months;
double rate = 0;
int counter = 0;
BankAccount::annualIntRate = rate;
cout << "How many months will the account be held for? ";
cin >> months;
counter = 0;
do
{
balance = accountBal * rate + accountBal;
counter++;
}while(months < counter);
cout << "Balance is:$" << accountBal << endl;
}
int main()
{
const int QUIT = 0;
const int MAX_ACCOUNTS = 10;
int counter;
int input;
int number = 0;
double balance = 0;
BankAccount accounts[MAX_ACCOUNTS];
//BankAccount display;
counter = 0;
do
{
accounts[counter].enterAccountData(number, balance);
cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
cin >> input;
counter++;
}while(input != QUIT && counter != 10);
accounts[counter].computeInterest();
system("pause");
return 0;
}
The constant field is easy enough:
class BankAccount
{
...
const static double annualIntRate = 0.03;
...
}
(Does your debugger complain about that? I'm using gcc 4.2.1) But there are other troubling things in your code, like the way computeInterest tries to set rate to zero, and the while loop... needs work.
EDIT:
One good principle is worth a hundred specific corrections. When you develop a complicated function, don't try to do it all at once; start with a simple piece, get that working perfectly, then build up. F'rinstance, computeInterest. You have several independent parts to get working: going through the while loop the correct number of times, calculating interest increments, keeping track of the balance-- right now computeInterest does none of these correctly. Tackle them one at a time, or in parallel if you want, but never combine parts that don't work.
boy it's been a LONG time since I've worked in C++, but I think all you have to do is this:
static double annualIntRate =.03;
in the "private" section of your code.
and then you can use annualIntRate as though it was a global (to each instance of the class) variable.