this is my first time posting here. I'm working on a lab for my CS II class (it's already past due, so I won't get any points for it at this point, but I'd still really like to understand what I'm doing wrong so that I can improve. The code is nowhere near complete, but I've hit a hangup that's keeping me from proceeding. Apologies in advance, I'm very rusty at this, and before I was rusty, I was very new. Also, I was up 'til about 4 in the morning trying to get this to work last night, so my code is probably pretty gnarly-looking at the moment.
Okay, so my issue is this: while single-stepping the code, the first function, getNoMonths, runs perfectly fine. It prompts the user for the number of months of sales they'd like to process the data for, and stores the number in no_Months back in main. The validation for the value needing to be between 3 and 6 also works fine.
When we get to getSales, the problem arises. The function prompts for the sales values of however many months the user defined earlier. It seems like it works perfectly. Upon closer inspection, however, it seems that only the first value is actually being stored in sales, which is supposed to be an array, the size of which is dynamically allocated according to how many months the user defined during getNoMonths.
I'm sure that whatever I'm doing wrong is incredibly simple, I can feel it. I've been flipping through the text again, trying to learn as much as I can about how arrays and dynamic memory allocation and pointers all work. I get the ideas behind them, but as you can probably see, I'm really struggling with the actual implementation.
I know that what I NEED to do here is:
set up an array to hold sales data for each month
have the size of that array match the number of months as input by the user
...I'm just not sure how to actually do it. I also know I need to have a pointer in order for the second bullet item to happen, but again, I'm not really clear on what exactly I need to do.
TL;DR I need some help getting this sales array to hold ALL the values input by the user, not just the first one. To do this, I'll probably need help with setting up a pointer to dynamically allocate the size of the sales array, and preferably an explanation on how the hell all this actually helps me and isn't just confusing and redundant, lol.
Source code follows:
//Jesse Holland
//Lab1Out
//Processes Sales Data, Displays as a Bar Graph presentation
#include <iostream>
#include "graph1.h"
using namespace std;
//FUNCTION PROTOTYPES
int getNoMonths(int& no_months); //prompts for number of months of sales data to be processed
void getSales(int* sales, int no_months); //prompts for sales data, stores corresponding data in "sales"
int getMax(int* sales, int no_months, double & max); //maximum value for "sales" array
int getMin(int* sales, int no_months, double & min); //minimum value for "sales" array
double getAvg(int* sales, int no_months, double & avg); //computes avg of sales data stored in "sales" array
void displayResults(int* sales, int no_months, int max, int min, double avg); //displays bar chart diagram
//MAIN FUNCTION START
int main()
{
double max = 0;
double min = 0;
double avg = 0;
int no_months = 0;
//prompt for number of months
getNoMonths(no_months);
//variable declaration
int * sales = new int[no_months];
//prompt for sales data
getSales(sales, no_months);
//maximum value of "sales" array
getMax(sales, no_months, max);
//minimum value for "sales" array
getMin(sales, no_months, min);
//computes avg of sales data stored in "sales" array
getAvg(sales, no_months, avg);
//displays bar chart diagram in graphics window
displayResults(sales, no_months, max, min, avg);
return 0;
}
//FUNCTIONS IMPLEMENTATION START
int getNoMonths(int& no_months) // int* months)
{
do
{
cout << "Please enter the number of months you'd like to process: <must be at least 3, but no more than 6>:";
cin >> no_months;
//int* months = new int[no_months];
}while ((no_months < 3) || (no_months > 6));
return no_months;
}
void getSales(int* sales, int no_months)
{
int count = 0;
for (count = 0; count < no_months; count++)
{
cout << "Please enter sales for month #" << (count + 1) << ": ";
cin >> sales[count];
}
}
int getMax(int* sales, int no_months, double & max)
{
//int max = 0;
for(int count = 0; count < no_months, count++;)
{
if (sales[count] > max)
max = sales[count];
}
return max;
}
int getMin(int* sales, int no_months, double & min)
{
//int min = 0;
int count = 0;
for (count = 0; count < no_months; count++)
{
if (sales[count] < min)
min = sales[count];
}
return min;
}
double getAvg(int* sales, int no_months, double & avg)
{
int sum = 0;
for(int count = 0; count < no_months; count++)
sum += sales[count];
return avg = (sum/no_months);
}
void displayResults(int* sales, int no_months, int max, int min, double avg)
{
cout << "The maximum is " << max << ". \n";
cout << "The minimum is " << min << ". \n";
cout << "The average is " << avg << ". \n";
}
Thanks very, very much in advance for any and all help. I'm very, very green at all this, and although I'm trying very hard to get it, it seems impossible. I'm determined to learn how all this works and to be able to UNDERSTAND it so I can replicate it myself, but right now I need a little help getting there. It's hard not having any friends that no anything about this stuff and a professor who isn't terribly interested in sitting down with me and helping me work it out, either. Anyway, I look forward to hearing from you guys and hopefully learning some stuff. Maybe one day I can learn enough to be able to return the favor to newer people than I.
UPDATE: Updated source code; average is being properly calculated and output now, but still can't get max and min to do the same. Thanks for the help thus far, any further input will of course be appreciated.
Your main problem seems to be
int no_months = 0; followed by int * sales = new int [no_months]; which basically allocates an array of size 0. Try calling getNoMonths before allocating the array and fix return types.
Related
I have made a program, which prints out numbers in a form of a shape.
I want to be able to calculate the sum of a selected row, e.g. I display a shape of 3 rows
1
1 2
1 2 3
1 2
1
If I wanted to calculate the sum of row 2, it will add 1 and 2 together to show the result.
How would I achieve this?
This is my code so far
#include <iostream>
using namespace std;
int main()
{
int i,k=0,n;
int space = n-1;
cout << "Enter amount of rows: ";
cin >> n;
while(k <= n)
{
for(i = 1; i <= k; i++)
cout<<i;
cout<<endl;
k++;
}
k=n;
while (k)
{
k--;
for (i = 1; i <= k; i++)
cout<<i;
cout<<endl;
}
return 0;
}
Since the numbers in each row begin with 1 and you know the total number of rows from the input n, the sum of numbers in each row can be easily calculated.
You can add the following code after the second while loop:
int rowNo; //For which the sum has to be calculated
cout << "Enter the row for which the sum has to be calculated" << endl;
cin >> rowNo;
int sum = 0;
int totalRows = n * 2 - 1;
if(rowNo <= totalRows)
{
if(rowNo > n)
rowNo = n - rowNo%n;
for (int i = 1; i <= rowNo; i++)
{
sum = sum + i;
}
cout << "Sum is " << sum << endl;
}
else
{
cout << "rowNo: "<< rowNo << " is greater than the total no of rows: " << totalRows << endl;
}
Once you printed all lines, there's no simple way to go back and calculate the sum of the numbers on a specific line.
The simplest way is to calculate the sums of the numbers of all lines (as you print them) and store in e.g. a vector. Then when you need to get the sum of a specific line just get the pre-calculated sum from the vector.
I'm not going to answer your homework for you but I'd like to give you a few ideas on how to improve your code and how to build a solution that is able to calculate the sum of the desired rows.
Don't simply print your shape when the user entered a number, rather build an object that contains the row information and can be printed.
class Shape {
...
private:
std::vector<Row> rows;
public:
Shape( int numberOfRows );
void Print();
...
}
A Row on the other hand could contain only the information about a single rows content
class Row {
...
private:
std::vector<int> content;
public:
void Print();
...
}
All you then need is to find implement a way of requesting a single Row from the Shape and calculate it's sum. The good thing about this way is, that you can easily repeat the 2. step and ask for different rows over and over again.
In your main you would then need to perform the following steps
Ask for the the number of rows
Create a Shape and print it to the screen
Ask a user for a row to calculate the sum of (maybe repetitively)
Calculate the sum and display it to the user (go back to 3. or exit)
EDIT:
I just read that you only had a few basics, so you probably haven't heard about classes yet. So your best bet IMO would be to store the shape in an array ( or an array of arrays ), btw. a std::vector<int> is somewhat similar to a C-Style array (int[]). Then you can still access the data after you have printed it and calculate the sum of a single row.
You are going to receive payments in the upcoming month. The payments are numbered from to and denotes the amount of money in dollars that will be paid in connection with the i-th payment. Before receiving the payments, you have two banking options to consider:
You can receive all the payments on your current bank account remembering that the bank charges you for each payment i max(k,x% of p_i ) , where k and x are given.
You can pay the bank d dollars upfront to open a new special account for which the bank doesn't charge you for any of the upcoming transactions.
Your task is to decide which of the above two options is more profitable to you. If both ways are equally profitable, then you prefer to be charged for each transaction.
Input Format
In the first line, there is a single integer,q denoting the number of scenarios to handle. After that, descriptions of all these scenarios follow. In the first line of a single scenario, there are space-separated integers . In the second line, there are space separated integers p_0,p_1,p_2,...p_(n-1).
Constraints:
1<=q<=5
1<=n<=100
1<=p_i<=1000
1<=k<=1000
1<=x<=100
1<=d<=100000
print fee if it's more profitable to use the current account and let the bank charge for each transaction, or print upfront if it's better to pay the bank up front for opening the new special account.
Below is my code: I am not sure why it does not cover all the cases, please enlighten me on this, thank you!
string feeOrUpfront(int n, int k, int x, long int d, vector <int> p)
{
double sum=0;
double amountcharged;
amountcharged=0;
for (int i=0;i<n;i++)
{
if ((p[i]*x/100)>k)
{amountcharged=p[i]*x/100;}
else
{amountcharged=k;}
sum=sum+amountcharged;
}
if (sum>d)
{
return "upfront";
}
else
{
return "fee";
}
}
int main() {
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
int n;
int k;
int x;
int d;
cin >> n >> k >> x >> d;
vector<int> p(n);
for(int p_i = 0; p_i < n; p_i++){
cin >> p[p_i];
}
string result = feeOrUpfront(n, k, x, d, p);
cout << result << endl;
}
return 0;
}
p[i]*x/100) is calculated multiple times and stored as double. Probably you want to calculate p[i]*x/100.0 as double.
In main the vector<int> p you can push the values to append them. So you don't need to access the container with the indexer.
Also you might avoid the for (int i loop in feeOrUpfront with an iterator and std::for_each.
IMHO Your question would match better at https://codereview.stackexchange.com/
How can I find the student’s age whose age equals to or is closest to the average age using vector? I have a function that also does sorting. this is what I have so far using C++ .
struct Student{
int age;
};
double getAveAge(vector<Student>&v)
{
int totalAge = 0;
int studentCount = v.size();
for(int x=0; x < studentCount; x++)
{
totalAge+= v[x].age;
}
return totalAge/studentCount;
}
double showMedian(vector<Student>v)
{
Student aStudent;
if (aStudent.age % 2 )
{
}else{
}
}
Loop through your vector<Student>, compare each one to the average, compare that score to the closest recorded score so far. If this student is the closest, update the closest recorded score and store the index number of that student. At the end of the loop, look up that student by the stored index number.
That's the English version anyway. And you might need to work on your abs :)
Im trying to write a console application in c++ that will let the user input a series of numbers and the program should get the sum of all numbers, the average number, the largest and the second largest number.
For example:
Enter a couple of numbers : 10 12 -5 20 -2 15 0
Sum = 50
Average value = 8.3
Largest number = 20
Second largest = 15
#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int a[5];
cout << "We are going to find the max value"<< endl;
int x;
for (x=0; x<5; x++)
{
cout<<"insert values"<<x+1<<endl;
cin>>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<5)
{
if (a[e]>max)
{
max = a[e];
}
e++;
}
cout<<"Max value in the array is.."<<max<<endl;
getch();
return 0;
}
This is my progress so far.
Although, I have some concerns.
How do I let the user input the numbers like in the example and store them in a array with unknown size?
I'll try to figure out a way to count the avg, sum and second largest while waiting for this answer :)
Thanks!
To input an unknown number of elements, you use std::vector, inputting
until the user tells you to stop, typically by inputting an end of file:
std::vector<int> values;
int i;
while ( std::cin >> i ) {
values.push_back( i ) ;
}
If you're looking for some other type a signal for the end, you'll
probably have to read line by line, checking whether the line contains
your end criteron, and then use std::istringstream to parse the
integer.
For the rest: it may not correspond to the goal of the exercise, but
the standard library has a couple of functions which could make things
significantly simpler: std::max_element, for example, or
std::accumulate. And <conio.h> is not very portable, and is
deprecated on the systems which do support it.
If you can't use std::vector, you might want to learn about dynamic memory allocation.
int *a = new int[size];
I am trying it this way. seems to be more simplified. just trying to figure out now how to include the month names and to get the program to output the name of the rainiest month not the number the user inputs.
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int a[12];
int x;
for (x=0; x<12; x++)
{
cout << "Insert days of rainfall for month "<<x+1<<endl;
cin >>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<12)
{
if (a[e]>max)
{
max = a[e];
}
else if (a[e]<min)
{
min = a[e];
}
e++;
cout<<"The rainiest month was " <<max<<endl;
cout<<"The least rainy month was " <<min<<endl;
getch ();
return 0;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Your average calculation is off a little, you have to take into consideration the order of operations when it comes to math. Multiplication and division are always done first, then addition and subtraction. What you end up with is that ONLY dec is divided by 12, and THEN you add all the other days to it. To fix this, you need to wrap the additions of all of the months in parentheses to force the addition to happen first, then do the divide after. In this case, you can just use your year variable since it is already all of the months added together and divide it by 12.
As far as your question goes, you want to show the highest and lowest values input, but I don't see any attempt to solve this in your code. I feel less inclined to just write the code for you so I will just give a brief explanation of what you need to do instead. Look at the value for each month, each time you look at the next month, you compare it with the current highest and current lowest values you remember. When the new month has a new higher, or new lower, value you replace the value you remember. Once you cycle through every month you will end up with your highest and lowest values.
The fastest and the most clean way is to use a container such as an std::vector. Then sort it using std::sort.
// Our container
std::vector<double> userInput;
// Populate the vector. Please don't cin into a double!
// Sort it.
std::sort (userInput.begin(), userInput.end());
// The highest value will be the last value in the vector
// whilst the lowest value will be the first one