Nested For Loop (C++) Not Working Properly - c++

I am working on some programming homework and I am trying to use a for-loop in order to facilitate the process of the coding. Here is the loop:
#ifndef DIVSALES_H
#define DIVSALES_H
class DivSales
{
public:
DivSales(){ quarterSales[4] = {0}; };
double getTotalSales() { return totalSales;}
static void setTotalSales(double);
static void addTotalSales(double);
double getQuarterSales(int numQuarter) {return quarterSales[numQuarter];}
void setQuarterSales(int numQuarter, double numAmount) { quarterSales[numQuarter] = numAmount;}
private:
static double totalSales;
double quarterSales[];
};
double DivSales::totalSales = 0;
void DivSales::setTotalSales(double totalAmount) {totalSales = totalAmount; }
void DivSales::addTotalSales(double addAmount) {totalSales += addAmount; }
#endif // DIVSALES_H
#include <iostream>
#include "DivSales.h"
using namespace std;
int main()
{
const int NUMDIVS = 6;
const int NUMQUARTERS = 4;
double amount = 0;
DivSales divs[NUMDIVS];
for(int division = 0; division < NUMDIVS; division++)
{
cout << "Division " << (division + 1) << endl;
for(int quarter = 0; quarter < NUMQUARTERS; quarter++)
{
cout << "Quarter " << (quarter + 1) << ": ";
cin >> amount;
divs[division].setQuarterSales(quarter, amount);
DivSales::addTotalSales(amount);
}
}
return 0;
}
Example of the output:
Division 1
Quarter 1: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2:
What I am trying to do is make it so that when I have input the numbers for the 4 quarters of a division, that it will move onto the next division. However, after 4 inputs it is not incrementing the division variable of the for-loop instead it continues asking for more inputs. What is going on?

I have found what's causing that problem, it is in the file DivSales.h:
Change this line:
double quarterSales[];
For this line:
double quarterSales[4];
The problem was that you were not allocating memory for an array of 4 elements. To initialize it, change your constructor to this:
DivSales():quarterSales({0}){ };
You should also move the following line to DivSales.cpp, because otherwise I was getting a multiple definition error:
double DivSales::totalSales = 0;

Here:
divs[division].setTotalSales(amount);
you probably want:
divs[division].addTotalSales(amount);
But that is not what is causing your problem. Which I cannot reproduce.

Related

Number always missing decimals after calculation

Sorry if this is summarized wrong and etc.. This is my first time asking a question on Stackoverflow, so if I'm making any mistakes, let me know.
Problem:
In line 20, code embedded below, I'm performing a calculation, more specifically this calculation: 11 * 50 / 100, which if I'm not mistaken should give a result of 5.5. But my console gives me a result of 5. Maybe it's because it's late, but I personally can't see a thing wrong in that line.
Or let me know if I'm using cout wrong.
Explanation of program:
You receive an input of five ages, a ticket cost 10, which results in 50. But you may substract the youngest persons age as percent from the final price.
Kind regards Olle!
using namespace std;
int main() {
int ages[5] = {11,18,19,30,34};
int ticketPrice = 10;
/*for (int i = 0; i < 5; ++i) {
cin >> ages[i];
}*/
int agesSize = *(&ages + 1) - ages;
int finalPriceWithoutDiscount = ticketPrice * agesSize;
int min;
min = ages[0];
for(int i=0;i< agesSize; i++){
if(ages[i] < min ){
min = ages[i];
}
}
double discount= min * finalPriceWithoutDiscount / 100;
cout << discount << endl;
// expected output from values:[min=11, fPWD = 50]
// 5.5
// actual output:
// 5.00000
double truePrice = finalPriceWithoutDiscount - discount;
cout << std::fixed << truePrice;
// my output:
// 45.00000
return 0;
}
In your calculation of discount, all operands (min, finalPriceWithoutDiscount and 100) are of type int. The operations performed are therefore integer operations. No decimals are produced.
The (integral) result of the calculation is then assigned to a floating point variable, and thus converted to floating point. But that happens after the computation has been performed in the integer domain.
To fix this problem, cast at least one of your operands to double. Or rather, since you’re using a literal (100), use a floating point literal:
double discount = min * finalPriceWithoutDiscount / 100.0;
This causes the operation involving 100.0 (that is, the division) to be performed on floating point numbers instead of integers.
The other answer actually answers your question, but I thought I'd contribute a more C++ example:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
std::vector<int> ages{11, 18, 19, 30, 34};
int ticketPrice = 10;
/*for (int i = 0; i < 5; ++i) {
cin >> ages[i];
}*/
int finalPriceWithoutDiscount = ticketPrice * ages.size();
int min = *std::min_element(ages.begin(), ages.end());
// Fix the calculation by using a double, 100.0
double discount = min * finalPriceWithoutDiscount / 100.0;
std::cout << discount << '\n';
// Fix by casting to double
double truePrice = static_cast<double>(finalPriceWithoutDiscount) - discount;
std::cout << std::fixed << truePrice;
return 0;
}

C++ expression must be an lvalue or a function designator

Here is my code I have looked up what to do multiple times and still haven't figured out what to do.
It keeps giving me this error: C++ expression must be an lvalue or a function designator with the part of the code :
avg_score = (float)*&get_average_score(score_1, score_2, score_3);`
how can i fix the error?
the original error was cannot convert a void to a float
avg_score = get_average_score(score_1, score_2, score_3);
how can i fix the error?`
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>
using namespace std;
void print_scores(int score_1, int score_2, int score_3);
void get_average_score(int score_1, int score_2, int score_3);
int main()
{
srand(time(NULL));
int score_1, score_2, score_3;
float avg_score;
score_1 = rand() % 21 + 20;
while (score_1 % 2 == 0)
{
score_1 = rand() % 21 + 20;
}
score_2 = rand() % 21 + 20;
score_3 = rand() % 21 + 20;
print_scores(score_1, score_2, score_3);
avg_score = (float)*&get_average_score(score_1, score_2, score_3);
cout << fixed << setprecision(1);
cout << "Average score = " << avg_score <<
endl;
return 0;
}
void print_scores(int score_1, int score_2, int score_3)
{
cout << "score 1 = " << score_1 << endl << "score 2 = " << score_2 << endl
<< "score 3 = " << score_3 << endl;
}
void get_average_score(int score_1, int score_2, int score_3)
{
(float)(score_1 + score_2 + score_3) / (float)3;
}
Your first mistake lies in the fact that you are trying to get a function that does not return a value to return a value. You've tried to reference a pointer *& which is not how you should be handling this as
1) you've tried to reference a pointer but instead you've done it on a function
2) you want a value, not a pointer so its the wrong approach.
If you need to use pointers (because thats the task at hand) then what you need to do is pass a reference to avg_score into your function.
void get_average_score(float * avg_score, int score_1, int score_2, int score_3)
{
*avg_score = (score_1 + score_2 + score_3) / 3.0;
}
and call it in main with:
get_average_score(&avg_score, score_1, score_2, score_3);
and dont forget to update the header declaration:
void get_average_score(float * avg_score, int score_1, int score_2, int score_3);
If you don't have to use pointers the easiest fix is to actually return a value.
Declare the function as type float :
float get_average_score(int score_1, int score_2, int score_3);
and edit the get_average_score function to be:
float get_average_score(int score_1, int score_2, int score_3)
{
return (score_1 + score_2 + score_3) / 3.0;
}
and get rid of (float)*& from main.
This means your function will return a float value that will be stored in avg_score on return.
Also note, by changing the denominator to 3.0 instead of 3 you don't need to don't need to type cast the result as a float.
Your coding style does come off as a little basic (which is ok, everyone has to start somewhere) but you have room for improvement, so take the time to learn now rather than struggling later (trust me it makes life easy in the long run).
Rather than making a function that will only work when you are averaging 3 numbers why not make a more modular function that would work for as many numbers as you want!
Try learning how to use vectors! If you're coming from C its kinda like an array but can be dynamically allocated i.e. any size you want.
Have a look around the net for some tutorials on what vectors are and how to use them.
I won't write out the code for this because you should learn how to do it your self (trust me you'll understand it better) but basically using a vector of int's std::vector<int> you can iterate through them all and add each element together and then at the end divide by the total number of elements (the number of iterations you do) to get your average!
**obviously theres a limit but thats a limit of your computer... *

finding pi - using Machin's formula. Different iterations are giving same result

I've written a few programs to find pi, this one being the most advanced. I used Machin's formula, pi/4 = 4(arc-tan(1/5)) - (arc-tan(1/239)).
The problem is that however many iterations I do, I get the same result, and I can't seem to understand why.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
double arctan_series(int x, double y) // x is the # of iterations while y is the number
{
double pi = y;
double temp_Pi;
for (int i = 1, j = 3; i < x; i++, j += 2)
{
temp_Pi = pow(y, j) / j; //the actual value of the iteration
if (i % 2 != 0) // for every odd iteration that subtracts
{
pi -= temp_Pi;
}
else // for every even iteration that adds
{
pi += temp_Pi;
}
}
pi = pi * 4;
return pi;
}
double calculations(int x) // x is the # of iterations
{
double value_1, value_2, answer;
value_1 = arctan_series(x, 0.2);
value_2 = arctan_series(x, 1.0 / 239.0);
answer = (4 * value_1) - (value_2);
return answer;
}
int main()
{
double pi;
int iteration_num;
cout << "Enter the number of iterations: ";
cin >> iteration_num;
pi = calculations(iteration_num);
cout << "Pi has the value of: " << setprecision(100) << fixed << pi << endl;
return 0;
}
I have not been able to reproduce your issue, but here is a bit cleaned up code with a few C++11 idioms and better variable names.
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
// double arctan_series(int x, double y) // x is the # of iterations while y is the number
// then why not name the parameters accoringly? In math we usually use x for the parameter.
// prefer C++11 and the auto notation wherever possible
auto arctan_series(int iterations, double x) -> double
{
// note, that we don't need any temporaries here.
// note, that this loop will never run, when iterations = 1
// is that really what was intended?
for (int i = 1, j = 3; i < iterations; i++, j += 2)
{
// declare variables as late as possible and always initialize them
auto t = pow(x, j) / j;
// in such simple cases I prefer ?: over if-else. Your milage may vary
x += (i % 2 != 0) ? -t : t;
}
return x * 4;
}
// double calculations(int x) // x is the # of iterations
// then why not name the parameter accordingly
// BTW rename the function to what it is supposed to do
auto approximate_pi(int iterations) -> double
{
// we don't need all of these temporaries. Just write one expression.
return 4 * arctan_series(iterations, 0.2) - arctan_series(iterations, 1.0 / 239.0);
}
auto main(int, char**) -> int
{
cout << "Enter the number of iterations: ";
// in C++ you should declare variables as late as possible
// and always initialize them.
int iteration_num = 0;
cin >> iteration_num;
cout << "Pi has the value of: "
<< setprecision(100) << fixed
<< approximate_pi(iteration_num) << endl;
return 0;
}
When you remove my explanatory comments, you'll see, that the resulting code is a lot more concise, easier to read, and therefore easier to maintain.
I tried a bit:
Enter the number of iterations: 3
Pi has the value of: 3.1416210293250346197169164952356368303298950195312500000000000000000000000000000000000000000000000000
Enter the number of iterations: 2
Pi has the value of: 3.1405970293260603298790556436870247125625610351562500000000000000000000000000000000000000000000000000
Enter the number of iterations: 7
Pi has the value of: 3.1415926536235549981768144789384678006172180175781250000000000000000000000000000000000000000000000000
Enter the number of iterations: 42
Pi has the value of: 3.1415926535897940041763831686694175004959106445312500000000000000000000000000000000000000000000000000
As you see, I obviously get different results for different numbers of iterations.
That method converges very quickly. You'll get more accuracy if you start with the smallest numbers first. Since 5^23 > 2^53 (the number of bits in the mantissa of a double), probably the maximum number of iterations is 12 (13 won't make any difference). You'll get more accuracy starting with the smaller numbers. The changed lines have comments:
double arctan_series(int x, double y)
{
double pi = y;
double temp_Pi;
for (int i = 1, j = x*2-1; i < x; i++, j -= 2) // changed this line
{
temp_Pi = pow(y, j) / j;
if ((j & 2) != 0) // changed this line
{
pi -= temp_Pi;
}
else
{
pi += temp_Pi;
}
}
pi = pi * 4;
return pi;
}
For doubles, there is no point in setting precision > 18.
If you want an alternative formula that takes more iterations to converge, use pi/4 = arc-tan(1/2) + arc-tan(1/3), which will take about 24 iterations.
This is another way if some of you are interested. The loop calculates the integral of the function : sqrt(1-x²)
Which represents a semicircle of radius 1. Then we multiply by two the area. Finally we got the surface of the circle which is PI.
#include <iomanip>
#include <cmath>
#define f(x) sqrt(1-pow(x,2))
double integral(int a, int b, int p)
{
double d=pow(10, -p), s=0;
for (double x=a ; x+d<=b ; x+=d)
{
s+=f(x)+f(x+d);
}
s*=d/2.0;
return s;
}
int main()
{
cout << "PI=" << setprecision (9) << 2.0*integral(-1,1,6) << endl;
}

C++ Getting a "symbols not found" error that I'm not familiar with

I'm getting the following error when I try to compile:
Undefined symbols for architecture x86_64:
"DivSales::corpSales", referenced from:
DivSales::CalculateDivTotal() in cc8xj4HM.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Any advise would be greatly appreciated. This is my first attempt at overloading an operator so I have a feeling the problem is there.
Also if there is a better way to achieve what I'm doing with the switch statement as well as the DivSales setter functions setFirst, setSecond, etc. I would love to hear about them. Thanks again. Here's all the code:
#include <iostream>
#include <string>
using namespace std;
class DivSales{
private:
double quarter[4]; // Holds the sales for each quarter
double first, second, third, fourth; // Store values from the inputs
static double corpSales; // Shared among all instances of DivSales (each object)
public:
// Populate the array quarter
void setQuartersArr(double first, double second, double third, double fourth){
quarter[0] = first;
quarter[1] = second;
quarter[2] = third;
quarter[3] = fourth;
}
void setFirst (double fir){
first = fir;
}
void setSecond (double sec){
second = sec;
}
void setThird (double thi){
third = thi;
}
void setFourth (double fou){
fourth = fou;
}
// Returns the sales of a particular quarter
double getSales(int quar){
double quarSales;
quarSales = quarter[quar];
return quarSales;
}
double CalculateDivTotal(){
double total = 0;
for(int count = 0; count < 4; count++) total += quarter[count];
corpSales += total;
return corpSales;
}
friend ostream &operator<<(ostream &out, DivSales divi6){
out << divi6.CalculateDivTotal();
return out;
}
};
int main()
{
int divNum = 6;
int quartCount = 1;
double tempSales;
DivSales divi1, divi2, divi3, divi4, divi5, divi6;
DivSales divisions[6] = {divi1, divi2, divi3,
divi4, divi5, divi6};
cout << "Welcome, please enter ";
for(int count = 0; count < divNum; quartCount++){
cout << "Division " << count + 1 << ", Quarter "
<< quartCount << " sales: ";
switch (quartCount){
case 1: cin >> tempSales;
divisions[count].setFirst(tempSales);
break;
case 2: cin >> tempSales;
divisions[count].setSecond(tempSales);
break;
case 3: cin >> tempSales;
divisions[count].setThird(tempSales);
break;
case 4: cin >> tempSales;
divisions[count].setFourth(tempSales);
count++;
quartCount = 0;
break;
}
tempSales = 0;
}
// Run the CalculateDivTotal method for each object except the last one
for(int count = 0; count < 5; count++) divisions[count].CalculateDivTotal();
cout << divi6.CalculateDivTotal();
return 0;
}
Statically declared class member variables must be defined in the C++ file.
Adding double DivSales::corpSales = 0; below the class solves the error.

Why am i getting this compile error when i try to compile?

I am some-what new to Programming in c++ i was assigned a exercise what i'm getting a compile error
i was hoping someone can either help me resolve the error or give me some insight as to why its happening
Code below
/*
Exercise 21 Intermediate: Declare a seven-row, two- column int array named temperatures.
The program should prompt the user to enter the highest and lowest temperatures for seven days.
Store the highest temperatures in the first column in the array.
Store the lowest temperatures in the second column.
The program should display the average high temperature and the average low temperature.
Display the average temperatures with one decimal place.
*/
#include <iostream>
#include <iomanip>
using namespace std;
//function prototype
void calcAverage(double temperatures[7][2]);
main()
{
double temperatures[7][2] = {0};
float high = 0.0;
float low = 0.0;
double high_average = 0.0;
double low_average = 0.0;
cout << "Please enter the high then low for the last 7 days " <<endl;
for(int x = 0; x < 6; x += 1)
{
cout << "Please enter the High for day: "<< x+1<<": ";
cin >> high;
temperatures[0][x] = high;
}
for(int x = 0; x < 6; x += 1)
{
cout << "Please enter the Low for day: "<< x+1<<": ";
cin >> low;
temperatures[1][x] = high;
}
//Error is here
calcAverage(high_average, low_average);
// end error
system("pause");
}
void calcAverage(double temperatures[6][1],double &high_average, double &low_average)
{
float accumulator = 0.0;
//for hot average
for(int x = 0; x < 6; x += 1)
{
accumulator += temperatures[0][x];
}
high_average = accumulator;
// for cold average
accumulator = 0.0;
for(int x = 0; x < 6; x += 1)
{
accumulator += temperatures[1][x];
}
low_average = accumulator;
}
44 cannot convert double' todouble ()[2]' for argument 1' tovoid calcAverage(double ()[2])'
void calcAverage(double temperatures[7][2]);
Okay, calcAverage takes a two-dimensional array of doubles.
calcAverage(high_average, low_average);
But you passed it two doubles.
void calcAverage(double temperatures[6][1],double &high_average, double &low_average)
And now it takes a two-dimensional array of doubles and two references.
Pick one of these three and stick to it.