Getting wrong output. Garbage value - c++

Problem is, on execution, the value of roundCost I'm getting is
something like -1220673834. I post the entire program because I'm not
sure where I'm going wrong.
Note: I was asked to take all variables as double type and later,
roundCost should be of type int. So I used type conversion there.
#include<iostream>
using namespace std;
class Restaurant{
private:
double tip, tax,totalCost,mealCost, tipPercent, taxPercent;
int roundCost;
public:
int tipCalc(double)
{
tip=mealCost*(tipPercent/100);
return tip;
}
int taxCalc(double)
{
tax=mealCost*(taxPercent/100);
return tax;
}
int totalCost1()
{
totalCost=mealCost+tip+tax;
return totalCost;
}
int roundCost1(double)
{
roundCost=(int)totalCost;
return roundCost;
}
}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;
Restaurant ob1;
cout<<"\n Enter mealCost \n";
cin>>mealCost;
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
ob1.roundCost1(totalCost);
cout<<"\n Round of cost is "<<roundCost<<endl;
return 0;
}

One thing you seem to be missing is that variables in your class have a different scope then variables in your main. You set the mealcost in your main from cin but you never passed this variable to the class. I changed this to be done using a constructor that sets the meal cost on creation. In every class you make you should always add a constructor. Also, you should be naming the variables your passing to functions and then using the same name in the function. For example in the tax percent function i pass double t, t is the percent, we then use t in the calculation. Your round cost variable was also private so you needed to output it via a function.
Also int functions will return a value, if you are using this type of function you should be assigning the return variable to something, but since you are just setting things in your class you can use void functions for most. The only time you use a value in the main is in the roundcost so this one is good to have it return a value. As it is int (which i assumed you wanted) it will get no decimal points and it will simply cut off any decimals in the total cost (ie 75.75 would become 75).
#include<iostream>
using namespace std;
class Restaurant{
private:
double tip, tax,totalCost,mealCost;
int roundCost;
public:
Restaurant (double m)
{
mealCost = m;
}
void tipCalc(double t)
{
tip=mealCost*(t/100.0);
}
void taxCalc(double t)
{
tax=mealCost*(t/100.0);
}
void totalCost1()
{
totalCost=mealCost+tip+tax;
}
int roundCost1()
{
roundCost=(int)totalCost;
return roundCost;
}
}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;
cout<<"\n Enter mealCost \n";
cin>>mealCost;
Restaurant ob1(mealCost);
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
cout<<"\n Round of cost is "<<ob1.roundCost1()<<endl;
return 0;
}
Try to do a bit more research next time by using a debugger, outputting cout statements regularly and searching for the errors you find but this will give you a working code this time.

Related

OOP problem related to default constructor having setter from cin and pointer to object doesn't return the name

I have 3 fields,one void method to return minimum price,constructor with 3 parameters and a getter for name.
a) First I need to create an instance for this constructor and to return the name and the minimum price which I did.
b) Secondly I need to create a default constructor(so no parameters) and a setter method to set the fields but from the keyboard.
c) In the end I need to do the same thing as at a) but by using a pointer.
My problem is:
I don't know how to make b) cuz the setter doesn't work and when I try to return the name of the pointer object from c) it doesn't show anyting
#include <iostream>
using namespace std;
class CTest{
private:
string name;
float price1;
float price2;
public:
CTest(string name,float price1,float price2){
this->name = name;
this->price1 = price1;
this->price2 = price2;
}
CTest(){};
void set_values(string name,float price1,float price2){
cin>>name;
cin>>price1;
cin>>price2;
}
string get_name(){
return name;
}
void minimum_price() {
if(this->price1 < this->price2)
cout<<"Min price is " <<this->price1;
else
cout<<"Min price is " <<this->price2;
}
};
int main(){
CTest P ("Phone",450.9f,500.9f);
cout<<P.get_name();
cout<<endl;
P.minimum_price();
CTest *A = new CTest("Something",4.5f,3.5f);
cout<<A->get_name();
cout<<endl;
A->minimum_price();
return 0;
}
So this is wrong
void set_values(string name,float price1,float price2){
cin>>name;
cin>>price1;
cin>>price2;
}
because the three parameters hide the names of the your class member variables. So the values from cin go to the parameters not to your class.
What you probably meant is this
void set_values(){
cin>>name;
cin>>price1;
cin>>price2;
}
Now the values from cin will go to your class.

I tried calling a function from other class and the output is garbled

im a newbie to c++ and im trying to calling a function of a class in another one but the output just doesnt come out right. I tried to calculate the total cost repeatedly according to different areas, but the output always garbled. i think i have declared it?
This is my code:
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<iomanip>
#include<numeric>
#include<conio.h>
using namespace std;
class RoomDimension
{
public:
double width;
double length;
double area;
double getarea(void);
void room(int,int);
};
double RoomDimension::getarea()
{
return area;
}
class RoomCarpet: public RoomDimension
{
public:
double costpermeter;
double totalcost=0;
double gettotalcost(void);
void calculation();
};
double RoomCarpet ::gettotalcost()
{
return totalcost;
}
void RoomDimension::room(int n, int m)
{
RoomCarpet rc;
cout<<"Number of rooms= ";
cin>>m;
if(m<1)
{
cout<<"Invalid input."<<endl;
}
for (n = 0;n < m;++n)
{
cout<<"Length of the room= ";
cin>>length;
if(length==0)
{
cout<<"Invalid input.";
return;
}
cout<<"Width of the room= ";
cin>>width;
if(width==0)
{
cout<<"Invalid input.";
return;
}
area=width*length;
cout<<"Area of the room= "<<area<<endl;
rc.calculation();
}
return;
}
void RoomCarpet::calculation()
{
RoomDimension rd;
totalcost=0;
cout<<"Price per square meter= ";
cin>>costpermeter;
if(costpermeter==0)
{
cout<<"Invalid input."<<endl;
return;
}
double totalcost=costpermeter*rd.area;
cout<<"Total price= RM"<<totalcost<<endl;
return;
}
int main()
{
RoomDimension rd;
rd.room(0,0);
return 0;
}
and the output keep showing like this
Number of rooms= 2
Length of the room= 5
Width of the room= 4
Area of the room= 20
Price per square meter= 5
Total price= RM5.03097e-317
Length of the room= 3
Width of the room= 7
Area of the room= 21
Price per square meter= 7
Total price= RM7.04336e-317
what should i do to fix that?
When I compile your code using MSVC, I get two warnings and an error:
line 29: Warning C26495 Variable 'RoomCarpet::costpermeter' is uninitialized. Always initialize a member variable (type.6).
line 76: Warning C6001 Using uninitialized memory 'rd'.
line 76: Error C4700 uninitialized local variable 'rd' used
Especially the last one is a problem
In the function RoomCarpet::calculation, you make (at least) two mistakes:
you declare a local variable rd, which is never initialized.
you declare and use a local variable totalcost, which hides the class member Roomcarpet::totalcost.
But that problem also occurs in RoomDimension::room, where you start by declaring local variable rc, but you never assign anything to it. When you then call rc.calculation();, you do calculations on unsigned variables.
You should rethink you design. Why is RoomCarpet a derivative of RoomDimension?

using the return value of one function as an argument in another function in c++

I found some related answers but couldn't understand it clearly because the codes were complicated for me.
In this program I used the dif () to find the difference in price then stored the return value total in variable difrnc. Then I used the difrnc variable as an argument for the function call
inflation=inflan(difrnc,lyp) //(calculates the inflation)
Instead of storing the total in variable difrnc can I directly use the answer from the function dif() as an argument for the function inflan() in its definition and how?
Sorry if it is a repeated question it would be great if someone could explain it using this program.
#include<iostream>
using namespace std;
double dif(double lp,double cp);//cp= current price,lp= last price, current
double inflan(double difference,double lastyp);
double cost(double cp,double inrate);
int main()
{
double lyp,cyp,difrnc,inflation,one_year_cost; // lyp = last year price,cyp=current year price,
for(int i=0;i>=0;i++)
{
cout<<"Enter current years price :";
cin>>cyp;
cout<<"Enter last Years price: ";
cin>>lyp;
difrnc=dif(lyp,cyp);
if(difrnc<0)
{
cout<<"price decreased by "<<difrnc<<endl;
}
else
{
cout<<"price increased by "<<difrnc<<endl;
}
inflation=inflan(difrnc,lyp);
one_year_cost=cost(cyp,inflation);
cout<<one_year_cost<<endl;
}
}
// to find the difference in price
double dif(double lp,double cp)
{
double total;
total=cp-lp;
return(total);
}
// to find the inflation
double inflan(double difference,double lastyp)
{
double inrate;
inrate=difference/lastyp;
return(inrate);
}
// to find estimated cost in one year
double cost(double cp,double inrate)
{
double
totalc=cp+inrate;
return(totalc);
}
Yes you can like this inflatio n = inflan(dif(lyp,cyp),lyp);
However, since you use the function returned value more than once, it make more sense to keep it as it is.
Aside from your current issue in your functions you can simplify them by removing their local variables and just simply return the evaluated expression.
For Example: You have this ->
double cost( double cp, double inrate ) {
double totalc = cp + inrate;
return totalc;
}
It is safe and efficient to do this instead:
double cost( double cp, double inrate ) {
return cp + inrate;
}
You can do that for any simple function that doesn't go through any loops.
As for your actual issue check out this quick program;
Sample.cpp
#include <iostream>
int five() {
return 5;
}
int ten() {
return 10;
}
int add( int a, int b ) {
return a + b;
}
int main() {
std::cout << add( five(), ten() ) << std::endl;
return 0;
}
Set a break point within the first line of your main function and step through the code line by line while examining your stack calls as well as your local and auto variables to see what is happening on each line of your functions to see the values that are being assigned to each variable.

Issue With My School Assignment on Classes

So I have an assignment due in my C++ class on classes, and I'm having some trouble. Here is the description of the assignment:
Programming Challenge 7 on page 499 of your text asks you to design and Inventory Class that can hold information for an item in a retail store's inventory. You are given the code for the creation of the class along with code for the implementation of the functions. Demonstrate the class by writing a simple program that uses it. This program should demonstrate that each function works correctly. Submit your .cpp file using the link provided.
And here are the contents of the file sent (it's quite lengthy):
// Chapter 7---Files for Programming Challenge 13---Inventory Class
// This is the inventory.h file.
// It contains the Inventory class declaration.
#ifndef INVENTORY_H
#define INVENTORY_H
class Inventory
{
private:
int itemNumber;
int quantity;
double cost;
double totalCost;
public:
// Default constructor
Inventory()
{ itemNumber = quantity = cost = totalCost = 0; }
// Overloaded constructor
Inventory(int, int, double); // Defined in Inventory.cpp
// Mutators (i.e., "set" functions) defined in Inventory.cpp
void setItemNumber(int);
void setQuantity(int);
void setCost(double);
// setTotalCost calculates the total cost
// and stores the result in the totalCost member
void setTotalCost()
{ totalCost = cost * quantity; }
// Accessors (i.e., "get" functions)
int getItemNumber()
{ return itemNumber; }
int getQuantity()
{ return quantity; }
double getCost()
{ return cost; }
double getTotalCost()
{ return totalCost; }
// Input validation functions
bool validInt(int);
bool validFloat(double);
};
#endif
// This is the inventory.cpp file.
// It contains the Inventory class function definitions.
#include <iostream>
#include "Inventory.h"
using namespace std;
//************************************************************
// Overloaded constructor
// Accepts arguments to be stored in each member variable.
//************************************************************
Inventory::Inventory(int in, int q, double c)
{
setItemNumber(in);
setQuantity(q);
setCost(c);
setTotalCost();
}
//************************************************************
// setItemNumber accepts an argument to be stored in item number.
//************************************************************
void Inventory::setItemNumber(int in)
{
while (!validInt(in))
{
cout << "Item Number must be positive. Please re-enter: ";
cin >> in;
}
itemNumber = in;
}
//************************************************************
// setQuantity accepts an argument to be stored in quantity.
//************************************************************
void Inventory::setQuantity(int q)
{
while (!validInt(q))
{
cout << "Quantity must be positive. Please re-enter: ";
cin >> q;
}
quantity = q;
}
//************************************************************
// setCost accepts an argument to be stored in cost.
//************************************************************
void Inventory::setCost(double c)
{
while (!validInt(c))
{
cout << "Cost must be positive. Please re-enter: ";
cin >> c;
}
cost = c;
}
//************************************************************
// The validInt member tests its integer argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validInt(int value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the integer value is valid
return true;
}
//************************************************************
// The validFloat member tests its floating-point argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validFloat(double value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the floating-point value is valid
return true;
}
I'm just not sure how to use this information to make a program that demonstrates the class, and it could be as simple as me not saving the file the correct way
Just write a main function which instantiates an Inventory object and calls each of its methods in a meaningful way. This isn't a puzzle, just find a way to call the functions that makes sense to you.

Not understanding the error message I'm getting

I doing a freind function program according to this book I have and I did a little of my own code to the program. I puzzle because I get this error message that the "room_num" is undeclared and intellisense identifier "room_num" is undefine. I need help in understanding why this is happen and how to fix it. Here is the code I have been working on for the passed three weeks.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
class HotelRoom
{
friend int Transfer( HotelRoom&, int);
private:
int room_num;
int transroom_num;
int room_cap;
int occup_stat;
double daily_rt;
public:
HotelRoom(int room, int roomcap, int occup, int transroom, double rate = 89.00);
~HotelRoom();
int Display_Number(); //Displays room number and add the method Display_Guest()
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
void Display_Guest();
};
HotelRoom::~HotelRoom()
{
cout << endl<<endl;
cout << "Guest in room "<<room_num << " has checked out." <<endl;
}
int HotelRoom::Display_Number()
{
return room_num;
}
int HotelRoom::Get_Capacity()
{
return room_cap;
}
int HotelRoom::Get_Status()
{
return occup_stat;
}
int HotelRoom::Change_Status(int occup)
{
occup_stat = occup;
if (occup > room_cap)
{
return -1;
}
else
return occup_stat;
}
double HotelRoom::Get_Rate()
{
return daily_rt;
}
double HotelRoom::Change_Rate(double rate)
{
daily_rt = rate;
return daily_rt;
}
int Transfer(HotelRoom& room_r1, int transroom)
{
//if guest transfers to different hotel room, room is vacant and transroom is now occupied
room_r1.room_num = room_r1.transroom_num;
return room_num;
}
int main()
{
cout<< setprecision(2)
<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint);
int room = 0;
int roomcap = 4;
int transroom;
int occup;
double rate = 89.00;
cout<<"\nEnter the room number: "<<endl;
cin>>room;
cout<<"\nEnter the amount of guest to occupy this room: "<<endl;
cin>>occup;
cout<<"\nThe guest has decided to transfer rooms"<<endl;
cout<<"\nEnter the room to transfer the guest to"<<endl;
cin>>transroom;
HotelRoom room1(room,roomcap, occup, transroom, rate ); //initialize the object
if (room1.Change_Status(occup) == -1)
{
cout<<"You have exceeded the room capacity"<<endl;
}
else
{
cout <<"\nThe room number is ";
room1.Display_Number();
cout<<"."<<endl;
cout<<"\nThe name of the primary guest is ";
room1.Display_Guest();
cout <<"."<<endl;
cout<<"\nThe number of guest in the room is "<<room1.Change_Status(occup)<<"." <<endl;
cout<<"\nThe daily rate for room "<<room<< " is "<<room1.Get_Rate()<<"."<<endl<<endl;
cout<<"\nYou have tranferred the guest from room"<<room1.Display_Number()<<"to" <<Transfer(room1,transroom)<<endl;
}
cout<<"\nRoom ";
room1.Display_Number();
cout<<" is vacant."<<endl;
system("PAUSE");
return 0;
}
The function Transfer is not a method of HotelRoom, still you are trying to access room_num in it as if it was. You need to specify which room_num of which HotelRoom instance you mean. Probably you meant return room_r1.room_num instead of return room_num.
Also in your Transfer function you never use the parameter transroom, instead you are using a transroom_num from room_r1. This is probably not what you want.
Finally you haven't implemented the constructor and DisplayRoom of HotelRoom. You should create a stubs, which do nothing or print warnings as long as you haven't implemented the methods properly, so you can at least compile and link the code.
Since you are a beginner I would just stick with member functions and class private variables until you get better at it.
As far as the error message, my guess is that inside the function you are using room_num does not have access to the private parts of the HotelRoom class. Notice I said guess, that's because you should copy and paste the text on the output window here so we can see what exactly is happening.
First, you have to identify that room_num is class member variable.
int Transfer(HotelRoom& room_r1, int transroom)
{
room_r1.room_num = room_r1.transroom_num;
//because room_num is not non class member variable, you have to write like below.
return room_r1.room_num;
//return room_num;
}
Secondly, you did not write definition HotelRoom::HotelRoom(int,int,int,int,double), HotelRoom::Display_Guest(void). So you have to write this constructor and function for avoiding error LNK2019.