Why are my calculations off? - c++

I'm practically done with this program. My only issue is my calculations, I guess. My numbers are completely off. I am too new to post an image, so here is the link to my output. Example: http://imageshack.us/photo/my-images/62/16902078.jpg/
NumDays.h
#ifndef NUMDAYS_H
#define NUMDAYS_H
#include <iostream>
#include <math.h>
using namespace std;
class NumDays
{
private:
double hours, days;
void calcDays();
public:
// Constructors
NumDays();
NumDays(double);
// Mutator Functions
void setHours(double);
// Accessor Functions
double getHours();
double getDays();
// Overloaded operator functions
NumDays operator + (const NumDays &); // Overloaded +
NumDays operator - (const NumDays &); // Overloaded -
NumDays operator ++ (); // Overloaded Prefix ++
NumDays operator ++ (int); // Overloaded Postfix ++
NumDays operator -- (); // Overloaded Prefix --
NumDays operator -- (int); // Overloaded Postfix --
};
#endif
NumDays.cpp
// Implementation file for the NumDays class
#include <iostream>
#include <math.h>
#include "NumDays.h"
using namespace std;
// Recalculation function
void NumDays::calcDays()
{
days = hours / 8;
}
// Default Constructor
NumDays::NumDays()
{
hours = 0;
days = 0;
}
// Constructor 1
NumDays::NumDays(double h)
{
hours = h;
days = hours * 1 / 8;
}
// Mutatory Functions
void NumDays::setHours(double h)
{
hours = h;
}
// Accessor Functions
double NumDays::getHours()
{
return hours;
}
double NumDays::getDays()
{
NumDays::calcDays();
return days;
}
// Overloaded operator functions
NumDays NumDays::operator + (const NumDays &a)
{
NumDays temp;
temp.hours = this->hours + a.hours;
return temp;
}
NumDays NumDays::operator - (const NumDays &a)
{
NumDays temp;
temp.hours = this->hours + a.hours;
return temp;
}
NumDays NumDays::operator ++ ()
{
++hours;
calcDays();
return *this;
}
NumDays NumDays::operator -- ()
{
--hours;
calcDays();
return *this;
}
NumDays NumDays::operator ++ (int)
{
NumDays temp(*this);
++hours;
return temp;
}
NumDays NumDays::operator -- (int)
{
hours--;
calcDays();
return *this;
}
main.cpp
#include <iostream>
#include "NumDays.h"
using namespace std;
int main()
{
double hours1, hours2;
//Prompt for the data for the first 2 objects
cout << "Enter the number of hours for the the object called One: ";
cin >> hours1;
cout << "Enter the number of hours for the the object called Two: ";
cin >> hours2;
// Define two objects of WorkHours
NumDays one(hours1), two(hours2);
cout << "One: " << one.getDays() << " day(s)" << endl;
cout << "Two: " << two.getDays() << " day(s)" << endl << endl;
// Demonstrate addition and subtraction operators
cout << "Three = One + Two: " << (one - two).getDays() << " day(s)" << endl;
cout << "One - Two: " << (one - two).getDays() << " day(s)" << endl << endl;
// Define a third and fourth object to be used for further operator demonstrations
NumDays three(one + two), four;
// Demonstrate increment and decrement operators
four = three++;
cout << "Four = Three++ " << endl;
cout << " Three: " << three.getDays() << " day(s)" << endl;
cout << " Four: " << four.getDays() << " day(s)" << endl << endl;
four = ++three;
cout << "Four = ++Three: " << endl;
cout << " Three: " << three.getDays() << " day(s)" << endl;
cout << " Four: " << four.getDays() << " day(s)" << endl << endl;
four = three--;
cout << "Four = Three--: " << endl;
cout << " Three: " << three.getDays() << " day(s)" << endl;
cout << " Four: " << four.getDays() << " day(s)" << endl << endl;
four = --three;
cout << "Four = --Three: " << endl;
cout << " Three: " << three.getDays() << " day(s)" << endl;
cout << " Four: " << four.getDays() << " day(s)" << endl;
system("pause");
return 0;
}

So, where is the implementation of your operator << function?
The code you posted contains none. You declared it as a friend in NumDays.h
friend ostream &operator << (ostream &, NumDays &);
but there's no definition for it either in NumDays.cpp or anywhere else.
Obviously, the linker is telling you that it can't find it. Neither can I.
You have to go to your NumDays.cpp and implement your operators << and >> there
ostream &operator << (ostream &s, NumDays &n)
{
// Whatever
return s;
}
istream &operator >> (istream &s, NumDays &n);
{
// Whatever
return s;
}

Related

No match for 'Operator<<'

In this program I got the error
[Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'numcall')
I can't understand how to get rid of it!!
#include<iostream>
using namespace::std;
class numcall
{
int a,b;
public:
numcall(int c,int d)
{
c = a;
c = b;
cout<<"Your First num is " << c << endl << "Your Second num is "<< d << endl;
cout << "You are in PARAMETER CONSTRUCTOR";
}
numcall(int u)
{
u = a;
b = 0;
cout << "Your First num is " << u << endl << "Your Second num is " << b << endl;
cout << "You are in PARAMETER CONSTRUCTOR";
}
numcall()
{
}
};
int main(void)
{
numcall x = numcall();
numcall y = numcall(3,4);
numcall z = numcall(3);
cout << x << endl << endl << y << endl << endl << z << endl;
}
You haven't defined the << operator for your class numcall, so the compiler doesn't know how to apply it.
So define it.
You need to define a friend method for the << stream operator, otherwise he doesn't know what to print.
friend ostream &operator<<(ostream &os, const numcall &numcall1) {
os << "a: " << numcall1.a << " b: " << numcall1.b;
return os;
}
This is just an example of implementation.
By the way there are other mistakes: c=a means assign a to c, you want to do the other way around. Welcome to the programming world mate ;)

Implementing a non-member IO operator

In my assignment I was asked to create the Product class, and I have finished all the implementations except the "non-member IO operator". The question I found it very vague, it asks me to overload the << and >> operators to work with ostream and istream to read a Product from and print a Product to the console in order to make this main function work.
Here I see the main function has cout or cin to Product's derived class SItem, I wonder how I should implement the << >> operators to make the main work.
My main:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include "Product.h"
#include <fstream>
#ifdef TAB
# undef TAB
#endif
#define TAB '\t'
using namespace std;
namespace sict {
class SItem :public Product {
public:
SItem(const char* theSku, const char * theName) :Product(theSku, theName) {}
SItem() {}
virtual std::fstream& store(std::fstream& file, bool addNewLine = true)const {
if (!isEmpty()) {
file.open("ms4.txt", ios::out | ios::app);
file << sku() << TAB << name() << TAB << quantity() << TAB << qtyNeeded() << TAB
<< int(taxed()) << TAB << price() << endl;
file.clear();
file.close();
}
return file;
}
virtual std::fstream& load(std::fstream& file) {
file.open("ms4.txt", ios::in);
char buf[2000];
double dbuf;
int ibuf;
file >> buf;
sku(buf);
file >> buf;
name(buf);
file >> ibuf;
quantity(ibuf);
file >> ibuf;
qtyNeeded(ibuf);
file >> ibuf;
taxed(ibuf != 0);
file >> dbuf;
price(dbuf);
file.clear();
file.close();
return file;
}
virtual std::ostream& write(std::ostream& os, bool linear)const {
return isEmpty() ? os : (os << sku() << ": " << name() << ", qty: "
<< quantity() << ", qtyNeeded:" << qtyNeeded()
<< ", Cost: " << fixed << setprecision(2) << cost());
}
virtual std::istream& read(std::istream& is) {
char buf[2000];
double dbuf;
int ibuf;
cout << "Sku: ";
is >> buf;
sku(buf);
cout << "Name (no spaces): ";
is >> buf;
name(buf);
cout << "Qty: ";
is >> ibuf;
quantity(ibuf);
cout << "Qty Needed: ";
is >> ibuf;
qtyNeeded(ibuf);
cout << "Is taxed? (1/0): ";
is >> ibuf;
taxed(ibuf != 0);
cout << "Price: ";
is >> dbuf;
price(dbuf);
return is;
}
};
}
void dumpFile(fstream& f) {
f.open("ms4.txt", ios::in);
char ch;
while (!f.get(ch).fail()) {
cout.put(ch);
}
f.clear();
f.close();
}
using namespace sict;
void test() {
double res, val = 0.0;
fstream F("ms4.txt", ios::out);
F.close();
SItem S;
SItem T;
SItem U;
cout << "Enter Product info: " << endl;
cin >> S;
SItem V = S;
S.store(F);
T.load(F);
cout << "T: (store, load)" << endl;
cout << T << endl;
cout << "S: " << endl;
cout << S << endl;
cout << "V(S): " << endl;
cout << V << endl;
cout << "U=T & op= :" << endl;
U = T;
cout << U << endl;
cout << "Operator == :" << endl;
cout << "op== is " << (T == "1234" ? "OK" : "NOT OK") << endl;
cout << "op+=: " << endl;
U += 10;
cout << U << endl;
cout << "op+=double : " << endl;
res = val += U;
cout << res << "=" << val << endl;
}
int main() {
fstream F("ms4.txt", ios::out);
F.close();
SItem S;
SItem U("4321", "Rice");
cout << "Empty Prouduct:" << endl << S << endl;
cout << "U(\"4321\", \"Rice\"):" << endl << U << endl;
cout << "Please enter the following information:" << endl;
cout << "Sku: 1234" << endl;
cout << "Name(no spaces) : Blanket" << endl;
cout << "Qty : 12" << endl;
cout << "Qty Needed : 23" << endl;
cout << "Is taxed ? (1 / 0) : 1" << endl;
cout << "Price : 12.34" << endl;
test();
cout << "Please enter the following information:" << endl;
cout << "Sku: 1234" << endl;
cout << "Name(no spaces) : Jacket" << endl;
cout << "Qty : 12" << endl;
cout << "Qty Needed : 23" << endl;
cout << "Is taxed ? (1 / 0) : 0" << endl;
cout << "Price : 12.34" << endl;
test();
dumpFile(F);
cout << "----The End" << endl;
return 0;
}
This is my Product.h:
namespace sict {
class Product : public Streamable {
char sku_[MAX_SKU_LEN + 1];
char * name_;
double price_;
bool taxed_;
int quantity_;
int qtyNeeded_;
public:
Product();
Product(const char*, const char*, bool = true, double = 0, int = 0);
Product(const Product&);
virtual ~Product();
Product& operator=(const Product&);
//setters
void sku(const char*);
void price(double);
void name(const char*);
void taxed(bool);
void quantity(int);
void qtyNeeded(int);
//getters
const char* sku()const;
double price()const;
const char* name()const ;
bool taxed()const;
int quantity()const;
int qtyNeeded()const;
double cost()const;
bool isEmpty()const;
//member operators
bool operator==(const char*);
int operator+=(int);
int operator-=(int);
};
double operator+=(double, const Product&);
std::ostream& operator<<(std::ostream& ostr, const Product& p);
std::istream& operator >> (std::istream& istr, Product& p);
}
All the functions have been implemented except the last two, which are the IO operators.
Streamable class is an abstract class that has no implementations.
You did this wrong in many ways.
Best approach in your case is do it like that.
First define interfaces for stream operations, for your products:
class IStreamPrintable
{
public:
virtual std::ostream& PrintToStream(std::ostream& outStream) const = 0;
};
class IStreamReadable
{
public:
virtual std::istream& ReadFromStream(std::istream& inputStream) = 0;
};
Secondly define stream operators which will use this interfaces.
std::ostream& operator<<(std::ostream& out, const IStreamPrintable& printObject)
{
return printObject.PrintToStream(out);
}
std::istream& operator>>(std::istream& input, IStreamReadable& readObject)
{
return printObject.ReadFromStream(input);
}
Now you Product can inherit this interfaces:
class Product
: public IStreamPrintable
, public IStreamReadable
{
…
};
You do not have to implement it immediately. You can implement those methods in specific product classes SItem and it will work out of the box.
Your method virtual std::fstream& store(std::fstream& file, bool addNewLine = true) is total mess. You are passing fstream object and opening some specific file on it. This is wrong since you are unable to write multiple objects to single file. Keep there ostream object and do not change is state (do only writing), so you could cascade calls and so you could avoid hard-coding a file name.

Why cant i overload the * operator? [duplicate]

This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 6 years ago.
#include <iostream>
#include <string>
using namespace std;
class sequence{
public:
sequence();
sequence(int x);
sequence& operator*=(const &left, const &right);
~sequence();
friend istream& operator >>(istream&, sequence&);
friend ostream& operator <<(ostream&, sequence&);
void set_num_samples(); //Set no. of samples
float* value; //pointer to float variable
void allocate_memory(); //Allocates memory
void set_values_array(); //Sets the values of an array
void check_array_input(float l); //Checks the values of the array
void reset_input(float j); //Resets the array
void de_allocate(); //deallocates memory
int get_num_samples();
void set_full_array(int x);
void calculate_full(float array1[], float array2[]);
void combine_seq_coef(sequence& inputvoltageA); //Combines the passed in sequence and coefficient
void combine_seq(sequence& objectcombine, int sample); // combine the sequences
private:
int num_samples; //number of samples in the object sequence
};
class FIR{
public:
FIR();
~FIR();
private:
int num_coefficients; //Number of coefficients in an FIR (filter impulse response)
};
//Constructor for each object
void sequence::set_num_samples() { //Set_num_sample definition
cout << "Please enter the number of values in your sequence: \n";
cin >> num_samples;
if(num_samples < 0){
cout << "Value entered must be greater than 0 "<< endl;
cout << "Please enter the value again: " << endl;
cin >> num_samples;
}
}; //ok (stream op)
void sequence::allocate_memory() {
value = new float[num_samples]; //Allocated memory for Array.
}; //ok
void sequence::set_values_array(){ //Set values for array
int k;
for(k=0; k<num_samples; k++){
cout << "Please enter a positive value for element : " << (k+1) << endl;
cin >> value[k];
while(value[k] < 0){
cout << "Enter positive value " << endl;
cin >> value[k];
}
}
cout << "Values have been assigned successfully! " << endl;
}; //ok
//Constructor functions
void sequence::check_array_input(float l) { //Checks array values.
cout << endl << "If you would like to check input values, enter 'y' otherwise, enter 'n' to continue..." << endl;
char check_value;
cin >> check_value;
if (check_value == 'y') {
int i;
for (i = 0; i < l; i++) {
cout << "Value no. " << (i + 1) << " is:" << endl;
cout << value[i] << endl;
}
}
}
void sequence::reset_input(float j) { //Reset voltage value and set to 0;
cout << endl << "If you would like to reset all input values, enter 'y' otherwise, enter 'n' to continue..."
<< endl;
char check_value2;
cin >> check_value2;
if (check_value2 == 'y') {
int i;
for (i = 0; i < j; i++) {
cout << "Value no." << (i + 1) << ": " << value[i];
value[i] = 0;
cout << " is set to 0!" << endl;
}
}
}
void sequence::de_allocate(){
delete[] value; //De-allocate memory
num_samples = 0;
cout << "De-allocation of input array successful, num of samples reset to 0! " << endl;
}
int sequence::get_num_samples(){
return num_samples;
}
/* void sequence::calculate_full(float array1[], float array2[]){
int loop;
for(loop=0; loop<num_samples; loop++){
cout << "CoefficientA value no: " << (loop+1) << ": " << array1[loop].value[loop] << endl;
cout << "InputvoltageA value no." << (loop+1) << ": " << array2[loop].value[loop] << endl;
value[loop] = (array1[loop].value[loop])*(array2[loop].value[loop]);
cout << "Combined value no. " << (i+1) << ": " << value[loop] << endl;
cout << "The combined value gives" << full[loop] << endl;
}
}; */
void sequence::set_full_array(int x){
num_samples = x;
}
void sequence::combine_seq(sequence& object_combine, int sample_num){
int loop;
for(loop=0; loop<sample_num; loop++){
}
};
sequence& sequence::operator*=(const &left, const &right){
int y = left.get_num_samples();
int x;
for (x=0; )
sequence = left.value * right.value
return sequence;
}
sequence::sequence(){ //SEQUENCE CONSTRUCTOR
set_num_samples();
allocate_memory();
set_values_array();
check_array_input(num_samples);
reset_input(num_samples);
de_allocate();
cout << endl << "Constructor complete!" << endl;
};
sequence::sequence(int a){ //sequence constructor 2
set_full_array(a);
allocate_memory();
}
/* sequence::sequence(int a){
set_full_samples();
allocate_memory();
int i;
for(i=0; i<num_samples; i++){
cout << "CoefficientA value no: " << (i+1) << ": " << coefficientA().value[i] << endl;
cout << "InputvoltageA value no." << (i+1) << ": " << inputvoltageA.value[i] << endl;
cout << "Combined value no. " << (i+1) << ": " << value[i] << endl;
}
}
*/
sequence::~sequence(){ //Destructor
cout << "Destructor is called" << endl;
}; //destructor
int main(){
// Create object, constructor called
// Constructor calls, set_num_sample, allocate_memory, set_values_array
// Enters values for voltage Inputs to the sequence into an array
// Checks values of the array
// Asks user if they want to reset values and set num samples = 0.
do {
cout << "Press the Enter key to continue:" << endl;
} while (cin.get() != '\n');
cout << "Input voltage sequence created!" << endl;
sequence inputvoltageA;
cout << endl << "CoefficientA sequence created!" << endl;
sequence coefficientA;
//Combines sequence and coefficients
cout << "If you would like to combine the coefficients with the input sequence A enter 'y', otherwise enter 'n'" << endl;
char prompt4;
cin >> prompt4;
if(prompt4 == 'y'){
int x = coefficientA.get_num_samples();
sequence full(x);
full = coefficientA*inputvoltageA;
}
/* Ask the user if they want to create new object
cout << "If you would like to create a new input voltage sequence enter 'y', otherwise enter 'n'" << endl;
char prompt3;
cin >> prompt3;
if(prompt3 == 'y'){
sequence inputvoltageB;
}
cout << "CoefficientA sequence created!" << endl;
sequence coefficientB;
*/
/*
cout << "If you would like to combine this sequence with the sequence before enter 'y', otherwise enter 'n'" << endl;
char prompt5;
cin >> prompt5;
if(prompt5 == 'y'){
combine_seq(inputvoltageA, num_samples);
} */
return 0;
}
Why cant i overload the * operator?
The compiler gives me the error c++ must have a type specifier.
My type specifier is a reference to a sequence object...
I think ive defined the overload operator * function correctly in the class and outside of it.
You're overloading operator*= not operator*. operator*= is a binary operator - you either need to:
define it as a friend binary function inside the class body;
friend auto& operator*=(sequence& l, sequence& r) { /* ... */ }
define it as a non-friend unary function inside the class body (where the left-hand side is implicitly *this);
auto& operator*=(sequence& r) { /* ... */ }
define it as a free binary function outside the class body.
auto& operator*=(sequence& l, sequence& r) { /* ... */ }
Also, your function parameters need types. const& left does not have a type - you probably want const sequence& left.

Arithmetic and Relational Operators

I followed my book to the T and for some reason when I try and run my program I get completely wrong output for the operator- and the operator+ for my output. Do you know what is going wrong with my Overloaded operator- and my overloaded operator+. The program compiles fine but the output is not right at all.
#include <iostream>
using namespace std;
class NumDays
{
private:
int ptrHours;
public:
NumDays(int H)// to set the pointer
{ setHours(H);}
void setHours(int H)
{ptrHours = H;}
int gethours() {return ptrHours;}
double calcDays()// function to calculate the days
{
double days;
days = ptrHours/8.0;
return days;
}
friend NumDays operator+(NumDays a, NumDays b);
friend NumDays operator-(NumDays a, NumDays b);
};
NumDays operator+(NumDays a, NumDays b)
{
return NumDays(a.ptrHours + b.ptrHours);
}
NumDays operator-(NumDays a, NumDays b)
{
return (a.ptrHours - b.ptrHours);
}
int main ()
{
NumDays first(0),
second(0),
third(0);
int hours1, hours2;
cout <<"Enter the how many hours you worked..." << endl;
cout <<"First set: ";
cin >> hours1;
while (hours1 < 0)
{
cout <<"\nYou cannot enter a negative value. " << endl;;
cin >> hours1;
}
first.setHours(hours1);
cout <<"Second Set: ";
cin >> hours2;
while (hours1 < 0)
{
cout <<"\nYou cannot enter a negative value. " << endl;;
cin >> hours2;
}
second.setHours(hours2);
cout <<"First set for days worked is " << first.calcDays() <<" days." << endl;
cout <<"Second set for days worked is " << second.calcDays() <<" days." << endl;
third = first - second;// where I try and do my arithmetic operators
cout <<"First - Second = " << cout << third.gethours() << endl;
third = first + second;
cout <<"First + Second = " << cout << third.gethours() << endl;
cin.ignore();
cin.get();
return 0;
}
The problem is in your code.
cout <<"First + Second = " << cout << third.gethours() << endl;
You shouldn't use cout inside a cout. Your print statement should be like this
cout <<"First + Second = " << third.gethours() << endl;
Hope this will help.
Thank you.

"No viable overloaded '=' " why?

I'm making a project for one of my classes and I'm pretty sure I'm almost done with the project. Basically I have to input 2 people's tickets and I have to find the maximum and minimum price. I need to overload the * and / operators to fix that issue for the project. Also, the friend declaration is a necessity for this project via teacher's instructions.
Now, for the issue. I'm trying to store the proper ticket variable (either t1 or t2) into t3 so I can return that to the main. When I use "=" to set either t1 to t3, it says "no viable overloaded '='". The following is my code:
#include <iostream>
using namespace std;
class ticket
{
public:
ticket();
double input();
double output();
friend ticket operator *(const ticket &t1, const ticket &t2);
friend ticket operator /(const ticket &t1, const ticket &t2);
private:
void cost();
string name;
double miles, price;
int transfers;
};
int main()
{
ticket customer1, customer2, customer3;
//------------------------------------------------
cout << "*** Customer 1 ***" << endl;
customer1.input();
cout << "--- Entered, thank you ---" << endl;
cout << "*** Customer 2 ***" << endl;
customer2.input();
cout << "--- Enter, thank you ---" << endl;
//------------------------------------------------
//------------------------------------------------
cout << "Testing of the * operator: " << endl;
customer3 = customer1 * customer2;
cout << "*** Database printout: ***" << endl;
customer3.output();
cout << endl;
cout << "--- End of Database ---" << endl;
//------------------------------------------------
//------------------------------------------------
cout << "Testing of the / operator:" << endl;
customer3 = customer1 / customer2;
cout << "*** Database printout: ***" << endl;
customer3.output();
cout << endl;
cout << "--- End of Database ---" << endl;
//------------------------------------------------
return 0;
}
ticket operator *(const ticket &t1, const ticket &t2)
{
ticket t3;
if (t1.price > t2.price)
t3 = t1.price;
else
t3 = t2.price;
return t3;
}
ticket operator /(const ticket &t1, const ticket &t2)
{
ticket t3;
if (t1.price < t2.price)
t3 = t1.price;
else
t3 = t2.price;
return t3;
}
ticket::ticket()
{
}
double ticket::input()
{
cout << "Miles? ";
cin >> miles;
cout << endl << "Transers? ";
cin >> transfers;
cout << endl << "Name? ";
cin >> name;
cost();
cout << endl << "Price is: " << price << endl;
return miles;
}
double ticket::output()
{
cout << name << '\t' << miles << "mi \t " << transfers << " transfers \t" << price;
return miles;
}
void ticket::cost()
{
price = (.5 * miles) - (50 * transfers);
}
You don't define an operator= for ticket that takes a double as its argument. As a consequence you can't assign doubles to ticket objects.
This is how I get the same compile error. I have mark one of my getter function as const while I still want to modify class member variable. See the following simple example:
class CPath {
private:
std::string m_extension;
public:
std::string GetExtension() const {
if (m_extension.length()==0) {
m_extension = "txt";
}
return m_extension;
}
}
In this case, we have two solutions:
1) drop const modifier in the function definition;
2) mark the property m_extension as mutable.
you might want to have member function
set_price(const& double price)
so you can change the error code like this,which would be better
if (t1.price > t2.price)
t3.set_price(t1.price);
else
t3.set_price(t2.price);