I am learning C++ from C++ primer Plus. I am currently doing OOP part exercises, and wrote a class which stores quarternal income as an array of doubles and minimum, maximum and average of values in an array. Class has 2 constructors:
1) Arguments: array of doubles and number of elements. Sets other values according to that array.
2)Default constructor: Asks for an element(using cin and cout). Checks for invalid input. If everythings fine, it increments number of elements. And loops that. Then it calls the first constructor with those arguments.
I then create an array of 2 Sales objects. First one is constructed via 1), and second one uses default. After that I print data on screen. First one prints correctly, but second one prints wrong double numbers in X*eY format. All I know is that if I check for array values at the end of 1), they're OK. If I do that at the end of default, they're weird.
Here is the code:
Code:
//sales.h
#ifndef sales_h_
#define sales_h_
namespace Sales
{
class Sales
{
private:
double quarters[4];
double min;
double max;
double average;
public:
Sales();
Sales(double *arr, int n);
void Show() const;
};
}
#endif
Code:
//def.cpp
#include "sales.h"
#include <iostream>
namespace Sales
{
Sales::Sales(double *arr, int n)
{
if (n == 0)
{
quarters[0] = 0;
min = 0;
max = 0;
average = 0;
}
else
{
if (n > 4)
n = 4;
for (int i = 0; i < n; ++i)
quarters[i] = arr[i];
for (int i = n; i < 4; ++i)
quarters[i] = 0;
min = quarters[0];
for (int i = 1; i < n; ++i)
if (quarters[i] < min)
min = quarters[i];
max = quarters[0];
for (int i = 1; i < n; ++i)
if (quarters[i] > max)
max = quarters[i];
average = 0;
for (int i = 0; i < n; ++i)
average += quarters[i];
average /= n;
}
}
Sales::Sales()
{
double temp[4];
int i = 0;
while (i < 4)
{
std::cout << "Enter value for quarter #" << i+1 << std::endl;
std::cin >> temp[i];
std::cin.get();
if (!std::cin.good())//check for invalid input
{
std::cin.clear();
while (std::cin.get() != '\n')
continue;
break;
}
if (temp[i] < 0)
break;
++i;
}
Sales(temp, i);
}
void Sales::Show() const
{
std::cout << "Sales: ";
for (int i = 0; i < 4; ++i)
std::cout << quarters[i] << " ";
std::cout << std::endl;
std::cout << "Minimum: " << min << std::endl;
std::cout << "Maximum: " << max << std::endl;
std::cout << "Average: " << average << std::endl;
}
}
Code:
//program.cpp
#include "sales.h"
#include <iostream>
int main()
{
double asd[] = {3.5, 6.5, 8.7};
Sales::Sales sal[2] = {Sales::Sales(asd, 3)};
sal[0].Show();
sal[1].Show();
std::cin.get();
return 0;
}
I'd be grateful if someone takes a look at this code. Sry for messiness and not commenting anything, and my English.