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.
Related
Hello once again stack overflow users! I have a new program, and have once again ran into a bit of a problem I cannot figure out! I wrote a program, math tutor program, which is practically finished, just that there are a few things I cannot figure out. In the program, there is a void function that checks the answers (will display if user input is correct or incorrect) but I cant seem to get it to work. When I have it in my doOneSet void function (does exactly one set or problems) it seems to only display "incorrect" even though the answer is correct? I cant seem to figure out what I did wrong or what is missing. Any type of help/tips/references is appreciated. Thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void getProbsPerSet (int& numProbs);
void printHeader (/*in*/ char problemType);
void getMaxNum(/* out */int& maxNum);
void generateOperands(int& num1, int& num2, int maxNum);
void checkAnswer (/* in */int num1,/* in */ int num2, /*out*/ int& answer);
void calcCorrectAnswer(/* in */ char problemType,/* in */ int num1,/* in */int num2, /*inout*/ int& answer);
void doOneProblem (char problemType, int maxNum);
void doOneSet (char problemType, int probsPerSet, int&);
void printReport (/* in */ int probsPerSet, int& set1Correct, /* in */int& set2Correct, /* in */int& set3Correct);
int main ()
{
int set1Correct, set2Correct, set3Correct, probsPerSet, maxNum;
srand(time(0));
getProbsPerSet (probsPerSet);
cout << endl;
doOneSet ('+', probsPerSet, set1Correct);
cout << endl;
doOneSet ('-', probsPerSet, set2Correct);
cout << endl;
doOneSet ('*', probsPerSet, set3Correct);
cout << endl;
return 0;
}
void getProbsPerSet (int& numProbs)
{
cout << "Enter problems per set: ";
cin >> numProbs;
cout << endl;
while (numProbs < 3 || numProbs > 10)
{
cout << endl;
cout << "Please stay between 3 and 10. Thank you!";
cout << endl;
cout << endl;
cout << "Enter problems per set: ";
cin >> numProbs;
cout << endl;
}
}
void printHeader (/*in*/ char problemType)
{
switch(problemType)
{
case '+': cout << endl;
cout << "Set # 1" << endl;
cout << "----------" << endl;
break;
case '-': cout << endl;
cout << "Set # 2" << endl;
cout << "----------" << endl;
break;
case '*': cout << endl;
cout << "Set # 3" << endl;
cout << " ----------" << endl;
break;
}
}
void doOneProblem (char problemType, int maxNum)
{
int num1,num2,answer;
generateOperands(num1, num2, maxNum);
switch (problemType)
{
case '+' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
case '-' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
case '*' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
}
}
void doOneSet (char problemType, int probsPerSet, int& answer)
{
int num1, num2, numProbs, maxNum;
bool isCorrect;
printHeader(problemType);
getMaxNum(maxNum);
for (int count = 0; count < probsPerSet; count++)
{
generateOperands(num1, num2, maxNum);
doOneProblem (problemType, maxNum);
calcCorrectAnswer(problemType, num1, num2, answer);
checkAnswer (num1, num2, answer);
}
}
void generateOperands(int& num1, int& num2, int maxNum)
{
num1 = 1 + rand() % maxNum;
num2 = 1 + rand() % maxNum;
}
void getMaxNum(/*out*/ int& maxNum)
{
cout << "What is the maximum number for this set?: ";
cin >> maxNum;
}
void checkAnswer (int num1, int num2, /*out*/ int& answer)
{
bool isCorrect;
if (answer == isCorrect)
{
cout << endl;
cout << "Correct!" << endl;
cout << endl;
}
else
{
cout << endl;
cout << "Incorrect!" << endl;
cout << endl;
}
}
void calcCorrectAnswer(/* in */ char problemType,/* in */ int num1,/* in */int num2, /*inout*/ int& answer)
{
bool isCorrect;
switch (problemType)
{
case '+' : isCorrect = num1 + num2;
break;
case '-' : isCorrect = num1 - num2;
break;
case '*' : isCorrect = num1 * num2;
break;
}
}
void printReport (/* in */ int probsPerSet, int& set1Correct, /*in*/ int& set2Correct, /*in*/ int& set3Correct)
{
int set1Percent = 0, set2Percent = 0, set3Percent = 0;
int total, complete;
int numcorrect = 1;
total = set1Correct + set2Correct + set3Correct;
complete = probsPerSet + probsPerSet + probsPerSet;
set1Percent = (100 * set1Correct) / probsPerSet;
set2Percent = (100 * set2Correct) / probsPerSet;
set3Percent = (100 * set3Correct) / probsPerSet;
cout << endl;
cout << "Set #1 : You got " << set1Correct << " correct out of " << probsPerSet << " for " << set1Percent << "%" << endl;
cout << "Set #2 : You got " << set2Correct << " correct out of " << probsPerSet << " for " << set2Percent << "%" << endl;
cout << "Set #3 : You got " << set3Correct << " correct out of " << probsPerSet << " for " << set3Percent << "%" << endl;
cout << endl;
cout << "Overall you got " << total << " out of " << complete << endl;;
}
The problem is your bool isCorrect;. Both of them. 😎
So, in one function, calcCorrectAnswer, you declare this variable, then set it according to the logic of your requirements. Fine.
Then in another function, checkAnswer, you declare it again, then compare it to true/false to choose which output to produce.
But these are different variables. Despite sharing a name, they are scoped to the function they're in, so setting one has no effect on the other. The one in checkAnswer is uninitialised and never takes a value, so your program has undefined behaviour.
You could return your boolean from calcCorrectAnswer and pass it as an argument to checkAnswer. Or you could just merge those two functions; there doesn't seem to be a big reason to keep them separate.
I'm studying functions in c++ form a book called "jumping to c++" and there are a problem exercise that is create a calculator and I need make the arithmetic operation in separate functions, sound easy and I think I did it 90% good, the program gives me the correct answer but with some random numbers.
the code is:
#include <iostream>
using namespace std;
int a, b;
int sum()
{
return a + b;
}
int subs()
{
return a - b;
}
int div()
{
return a / b;
}
int mult()
{
return a * b;
}
int ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
int main()
{
int opcion;
cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
cin >> opcion;
if(opcion == 1)
{
cout << ask();
cout << "The result is: " <<sum() <<"\n\n";
} else if (opcion == 2)
{
cout << ask();
cout << "The result is: " << subs() <<"\n\n";
}else if (opcion == 3)
{
cout <<ask();
cout << "The result is: " << div() <<"\n\n";
}else if(opcion == 4)
{
cout << ask();
cout << "The result is: " << mult() <<"\n\n";
}else
{
cout << "Error.\n\n";
}
system("pause");
}
and this is the "error/bug/whatever"
1. Sum
2. Substraction
3. Division
4. Multiplication
Choose one option from above:
4
Give me the first number: 5
Give me the second number: 5
1878005856The result is: 25
Press any key to continue . . .
notice the error before of "The result is:"
appreciate any help, thanks
ask() does not return anything so it should be a void. Also, you do not need to do cout << ask(); since ask() already does the printing inside of it and it is a void (now) so it can't be printed.
Here is the code with the modifications, see comments with **** in front for changes:
#include <iostream>
using namespace std;
int a, b;
int sum() {
return a + b;
}
int subs() {
return a - b;
}
int div() {
return a / b;
}
int mult() {
return a * b;
}
void ask() { // **** Changed to void here
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
int main() {
int opcion;
cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
cin >> opcion;
if (opcion == 1) {
ask(); // **** Removed cout <<
cout << "The result is: " << sum() << "\n\n";
} else if (opcion == 2) {
ask(); // **** Removed cout <<
cout << "The result is: " << subs() << "\n\n";
} else if (opcion == 3) {
ask(); // **** Removed cout <<
cout << "The result is: " << div() << "\n\n";
} else if (opcion == 4) {
ask(); // **** Removed cout <<
cout << "The result is: " << mult() << "\n\n";
} else {
cout << "Error.\n\n";
}
system("pause");
}
You can try it here
The random number was caused by you doing cout << ask(); even though you had not returned anything.
As aschepler pointed out "make sure you enable and read compiler warnings - there should be one saying that ask() doesn't return anything although declared to return an int."
The problem is your int ask() function.
It must return int value which you are writing to console with cout << ask();
The answer above won't work because you cannot write void to cout.
Since you do not return a value then a random number retruned. My compiler marks that as an error.
Replace type of ask function:
void ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
Then replace cout << ask(); in every if statement with just ask();
Like this:
if (opcion == 1)
{
ask();
cout << "The result is: " << sum() << "\n\n";
}
else if (opcion == 2)
{
ask();
cout << "The result is: " << subs() << "\n\n";
}
else if (opcion == 3) ...
Consider checking if b==0 in case of devision operation. Or your program will crash if u try to devide by zero.
this function is returning a random integer. convert it to void
int ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
new
void ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
I'm working on a project by where I have to create a simple program that works based of the user input. I've gone with a basic calculator but I'm having trouble getting my if/else if statements to work. Basically, if the user types in "Addition", I want the program to say "...I will help you with addition!", and so on for whether the user says "Subtraction", "Division", and "Multiplication".
I'm new to this and so this has already taken me hours upon hours, not looking for you to do it for me but to point out my erorrs and advise so that I can learn from it will be great.
TIA.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
//user inputs what he needs help with/program output
char Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of assistance today?" << endl;
char inpsum[20];
cin >> inpsum;
char output;
if (inpsum == "Addition")
{
cout << "Great! I'll help you with addition!" << endl;
}
else if (inpsum == "Subtraction")
{
cout << "Great! I'll help you with subtraction!" << endl;
}
else if (inpsum == "Division")
{
cout << "Great! I'll help you with division!" << endl;
}
else if (inpsum == "Multiplication")
{
cout << "Great! I'll help you with multiplication!" << endl;
}
return 0;
REST OF CODE
//addition function
void Add() {
float add1, add2;
cout << "Please enter two values you want added together" << endl;
cin >> add1;
cin >> add2;
cout << "The answer is: " << (add1 + add2) << endl;
}
//subtraction function
void Subt() {
float subt1, subt2;
cout << "Please enter two values you want subtracted" << endl;
cin >> subt1;
cin >> subt2;
cout << "The answer is: " << (subt1 - subt2) << endl;
}
//division function
void Div()
{
float div1, div2;
cout << "Please enter two values you want divided" << endl;
cin >> div1;
cin >> div2;
cout << "The answer is: " << (div1 / div2) << endl;
}
//multiplication function
void Mult() {
float mult1, mult2;
cout << "Please enter two values you want multiplacted" << endl;
cin >> mult1;
cin >> mult2;
cout << "The answer is: " << (mult1 * mult2) << endl;
}
int main()
{
Inpsum(); //user inputs what they want help with
Add();
Subt();
Div();
Mult();
return 0 ;
}
This code is all wrong you need to learn about C++ correctly first, here is the corrected code
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include<string>
using namespace std;
//addition function
float Add(float add1, float add2)
{
return (add1 + add2);
}
//subtraction function
float Subt(float subt1, float subt2) {
return (subt1 - subt2);
}
//division function
float Div(float div1, float div2)
{
return (div1 / div2);
}
//multiplication function
float Mult(float mult1, float mult2)
{
return (mult1 * mult2);
}
void input(float &num1, float &num2)
{
cout << "\nEnter First Number : ";
cin >> num1;
cout << "Enter Second Number : ";
cin >> num2;
}
//user inputs what he needs help with/program output
void Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of assistance today?" << endl;
float num1;
float num2;
string inpsum;
cin >> inpsum;
if (inpsum == "adding")
{ //if user enters "adding"
cout << "Great!, I will help you with " << (inpsum) << endl;
input(num1, num2);
cout << "\nAnser Is " << Add(num1, num2);
}//then output = "...i will help with adding"
else if (inpsum == "subtraction") //otherwise, if user enters "subtraction"
{
cout << "Great!, I will help you with " << (inpsum) << endl; //then output = "...i will help with subtraction"
input(num1, num2);
cout << "\nAnser Is " << Subt(num1, num2);
}
else if (inpsum == "division") //if user enters "division"
{
cout << "Great!, I will help you with " << (inpsum) << endl; ////then output = "...i will help with division
input(num1, num2);
cout << "\nAnser Is " << Div(num1, num2);
}
else if (inpsum == "multiplication") //if user enters "muliplication"
{
cout << "Great, I will help you with " << (inpsum) << endl; ////then output = "...i will help with multiplication"
input(num1, num2);
cout << "\nAnser Is " << Mult(num1, num2);
}
else
{
cout << "Enter A Correct Mathematical Operation";
}
}
int main()
{
Inpsum(); //user inputs what they want help with
cout<<endl;
system("pause");
return 0;
}
First of all, instead of using char array, use std::string.
Secondly, if-else statements have syntax errors.
Basic structure of if-else statements is like
if(condition)
{
//code
}
else
if(condition)
{
//code
}
More on if-else statements in C++
I have been assigned a project that I am having trouble figuring out the issue. The project is :
"The main() function, which shall ask for input from the user to compute the following: SumProductDifference and Power. There should be a well designed user interface. A void function called SumProductDifference(int,int,int&,int&,int&) that computer the sum, product, and difference of two input arguments, and passes the sum, product and difference by-reference. A value returning function called Power(int a, int b) that computes a raised to the b power. Design and implement your own power function using an iterative control structure, or even recursion. Do no simply write a wrapper around the C++ function called pow(). There should be a user loop and a menu so that the user can select either SumProductDifference, Power, or Quit. The menu should also provide options of allowing the user to set and change the values of the two input integers.
#include "stdafx.h"
#include <iostream>
using namespace std;
void SumProductDifference(int, int, int&, int&, int&);
int Power(int a, int b);
bool GoAgain();
int main() {
int a, b;
int choice;
int sum, product, difference;
do
{
cout << "================================================" << endl;
cout << "=====Welcome to AB Calculator 2016 Edition======" << endl;
cout << "==== 1 - SumProductDifference Function ======" << endl;
cout << "==== 2 - Power of Function ======" << endl;
cout << "==== 3 - Quit ======" << endl;
cout << "= Make A Selection: ======" << endl;
cout << "================================================" << endl;
cin >> choice;
switch (choice) {
case '1': SumProductDifference(a, b, sum, product, difference);
break;
case '2': Power(a, b);
break;
case '3':
break;
default:
break;
}
return 0;
} while (choice != 3);
return 0;
}
bool GoAgain() {
char answer;
cout << "would you like to go again (y/n) ==> ";
cin >> answer;
return answer == 'y';
}
void SumProductDifference(int a, int b, int& s, int& p, int& d) {
cout << "Enter two integers: ";
cin >> a, b;
s = a + b;
p = a * b;
d = a - b;
cout << "The sum of " << a << " + " << b << " = " << s << endl;
cout << "The product of " << a << " * " << b << " = " << p << endl;
cout << "The difference of " << a << " - " << b << " = " << d << endl;
}
int Power(int a, int b) {
int total = 1;
int i;
cout << "Enter a number: ";
cin >> a;
cout << "Raise this integer to the power of: ";
cin >> b;
for ( i = 1; i < b; i++) {
total = total *b;
}
return total;
}
Declaring int choice; but in the switch - case '1'?
You are reading int but comparing it to a char literal.
Either change int choice; --> char choice; or case '1' --> case 1:
Read about fundamental types in C/C++.
Char is just a 8bit integer, which we conveniently choose to represent a character (with the agreement of the compiler).
Also you are not reading correctly multiple values from std::cin: cin >> a, b; and several other errors.
Learn to research correctly. Consult cppreference.com before you ask SO.
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;
}