In this program Iam trying to take 78 degrees Fahrenheit and return them in a class with the Celsius version and kelvin. But for some odd reason I'm just getting this as the output. What am I doing wrong?
This is my output.
78
0
273.15
#include <iostream>
using namespace std;
class Temperature
{
public:
double getTempKelvin();
double getTempFahrenheit();
double getTempCelcius();
void setTempKelvin(double k);
void setTempFahrenheit(double f);
void setTempCelcius(double c);
private:
double kelvin, fahrenheit, celcius;
double c, f, k;
};
int main ()
{
double c, f, k;
Temperature Conv;
Conv.setTempFahrenheit(f);
Conv.setTempCelcius(c);
Conv.setTempKelvin(k);
cout << Conv.getTempFahrenheit() << endl;
cout << Conv.getTempCelcius() << endl;
cout << Conv.getTempKelvin() << endl;
return 0;
}
void Temperature::setTempFahrenheit(double f)
{
f = 78;
fahrenheit = f;
}
void Temperature::setTempCelcius(double c)
{
c = (5/9) * ( f - 32);
celcius = c;
}
void Temperature::setTempKelvin(double k)
{
k = c + 273.15;
kelvin = k;
}
double Temperature::getTempFahrenheit()
{
return fahrenheit;
}
double Temperature::getTempCelcius()
{
return celcius;
}
double Temperature::getTempKelvin()
{
return kelvin;
}
5/9 is integer division and will result in 0. You need to use doubles, Try:
void Temperature::setTempCelcius(double c)
{
c = (5.0/9.0) * ( f - 32);
celcius = c;
}
Aside from the 5/9 issue, you have three sets of variables called 'c', 'f', and 'k'. One set are the member variables in the class. Another set are the variables in main. The third set are the parameters inside the various get* functions.
It's not clear what purpose the variables in main serve, why the functions take parameters at all, or why your class has two sets of variables for the temperatures (both c and celsius, and so on) but if you give the sets of variables different names, it will become easier to understand why your program isn't working.
Seems that my problem was that i was clearning the k c and f double so i just removed them from the functions.
#include <iostream>
using namespace std;
double c, f, k;
class Temperature
{
public:
double getTempKelvin();
double getTempFahrenheit();
double getTempCelcius();
void setTempKelvin();
void setTempFahrenheit();
void setTempCelcius();
private:
double kelvin, fahrenheit, celcius;
double c, f, k;
};
int main ()
{
Temperature Conv;
Conv.setTempFahrenheit();
Conv.setTempCelcius();
Conv.setTempKelvin();
cout << Conv.getTempFahrenheit() << endl;
cout << Conv.getTempCelcius() << endl;
cout << Conv.getTempKelvin() << endl;
return 0;
}
void Temperature::setTempFahrenheit(){
f = 78;
fahrenheit = f;
}
void Temperature::setTempCelcius()
{
c = (5.0/9.0) * ( f - 32);
celcius = c;
}
void Temperature::setTempKelvin()
{
k = c + 273.15;
kelvin = k;
}
double Temperature::getTempFahrenheit()
{
return fahrenheit;
}
double Temperature::getTempCelcius()
{
return celcius;
}
double Temperature::getTempKelvin()
{
return kelvin;
}
#include<iostream>
using namespace std;
class temperature
{
public :
virtual void calculate(float)=0;
};
class ftoc : public temperature
{
public :
float c;
void calculate(float f)
{
c=(f-32)*5/9;
cout<<"Temperature in celcius is : "<<c<<" `C "<<endl;
}
};
class ftok : public temperature
{
public :
float k;
void calculate(float f)
{
k=(f+459.67)*5/9;
cout<<"Themperature in kelvin is : "<<k<<" K "<<endl;
}
};
int main()
{
float f;
ftoc a;
ftok b;
cout<<"Enter the temperature : ";
cin>>f;
a.calculate(f);
b.calculate(f);
return 0;
}
Related
I'm working on a programme to calculate average acceleration and i use 3 function ( by pass reference method) after writing my code this error happens
and "error C2082: redefinition of formal parameter 'Vo'".I've google it and i barely understand it.Can anyone explain to me why this happens and how to solve this?thank you for helping
/* lab assessment 4 kiraan pecutan*/
#include <iostream>
using namespace std;
void data(double& Vo,double& Vt,double& t);
void calculate(double& sum);
void output(double& out);
double Vo,Vt,t,sum,out;
int main()
{
cout<<"please enter your velocity(Vo=m/s)\n,velocity(Vt=m/s)\nand time(s=second)\n\n";
data(Vo,Vt,t);
calculate(sum);
output( out);
return 0;
}
void data(double& Vo,double& Vt,double& t)
{
double Vo,Vt,t;
cin>>Vo;
cin>>Vt;
cin>>t;
cout<<"your Vo="<<Vo<<" ,Vt="<<Vt<<" and T="<<t<<"\n\n";
}
void calculate(double& sum )
{
double Vt,Vo,t;
sum=(Vt-Vo)/t;
}
void output(double& out)
{
double sum;
cout<<"the acceleration ="<<sum;
}
You declare variables with the same name multiple times. Each variable defined by its name should be declared exactly ones. It is not allowed to use the same variable name e.g. as a function parameter and a variable name in the function body, e.g.
void data(double &Vo) {
double Vo = 0.0; // Vo already exists with type double&
// do something
}
Please consider the following hints:
do not use global variables unless necessary, they are hard to debug in big projects
always initialize variables of basic types (int, float, double, ...) with a value otherwise they get a 'random' one
The following code should compile without errors, even though the semantic/computation maybe wrong. I just used your implementation.
#include <iostream>
using namesace std;
//--------------------------------------------------------------------------//
void data(double &Vo, double &Vt, double &t);
void calculate(double &Vo, double &Vt, double &t, double &sum);
void output(double &out);
//--------------------------------------------------------------------------//
int main() {
double Vo = 0.0;
double Vt = 0.0;
double t = 0.0;
double sum = 0.0;
double out = 0.0;
cout << "please enter your velocity(Vo=m/s)\n,velocity(Vt=m/s)\nand time(s=second)\n\n";
data(Vo, Vt, t);
calculate(Vo, Vt, t, sum);
output(out);
return 0;
}
//--------------------------------------------------------------------------//
void data(double &Vo, double &Vt, double &t) {
cin >> Vo;
cin >> Vt;
cin >> t;
cout << "your Vo=" << Vo << " ,Vt=" << Vt << " and T=" << t << "\n\n";
}
//--------------------------------------------------------------------------//
void calculate(double &Vo, double &Vt, double &t, double &sum) {
sum = (Vt - Vo) / t;
}
//--------------------------------------------------------------------------//
void output(double &out) {
cout << "the acceleration =" << out;
}
I have been trying to code a program that can solve for c using the Law Of Cosines. The program runs correctly, but the answer I get is ridiculously big, noted by how it was in scientific notation.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
class TrigMath
{
private:
double a;
double b;
double y;
public:
double LawOfCos()
{
return sqrt(pow(a,2) + pow(b,2) - 2*a*b*cos(y));
}
void seta(double A)
{
A = a;
}
void setb(double B)
{
B = b;
}
void sety(double Y)
{
Y = y;
}
};
int main()
{
TrigMath triangle1;
triangle1.seta(3);
triangle1.setb(4);
triangle1.sety(60);
cout << "c is equal to " << triangle1.LawOfCos() << endl;
return 0;
}
The cos() function there takes input as radians not as degrees.
Try to convert degrees to radians and then supply it as input.
In the class functions seta, setb and sety you have written A = a, B = b and Y = y.
You have to change them to a = A, b = B and Y = y.
So after applying all the changs the code should be like
#include <iostream>
#include <cmath>
using namespace std;
class TrigMath
{
private:
double a = 0;
double b = 0;
double y = 0;
public:
double LawOfCos()
{
return sqrt(pow(a,2) + pow(b,2) - 2*a*b*cos(y));
}
void seta(double A)
{
a = A;
}
void setb(double B)
{
b = B;
}
void sety(double Y)
{
y = Y*3.14/180;
}
};
int main()
{
TrigMath triangle1;
triangle1.seta(3.0);
triangle1.setb(4.0);
triangle1.sety(60.0);
cout << "c is equal to " << triangle1.LawOfCos() << endl;
return 0;
}
I need help containing the data inputted with dollars and cents. I've been trying by putting it in a total_money equation, but I'am stuck. For example, when I deposit 30 dollars I want it to stay there so when I go back in a deposit 10 dollars I get 40.
This is all about depositing and withdrawing money from a bank account while it keeps track of the total money left in the account by using classes.
#include <iostream>
using namespace std;
class SavingsAccount
{
public:
SavingsAccount();
SavingsAccount(int d, int c);
void deposit(int d, int c);
void withdraw(int d, int c);
void total(int d, int c);
void set(int dollars, int cents);
void convert(int d, int c);
private:
double total_money;
int dollars;
int cents;
};
SavingsAccount::SavingsAccount()
{
dollars = 0;
cents = 0;
}
void SavingsAccount::set(int dollars, int cents)
{
}
int main()
{
SavingsAccount bank1, bank2(50, 88);
int dollars, cents;
bank1.set(30, 65);
bank2.set(0, 0);
int anwser;
cout << "Would you like to 1.Deposit or 2.Withdraw?";
cin >> anwser;
if (anwser == 1)
{
cout << "Enter in how much you want to deposit in dollars:";
cin >> dollars;
cout << "Enter in how much you want to deposit in cents:";
cin >> cents;
if (dollars < 0 || cents < 0)
{
cerr << "Invalid!" << endl;
exit(1);
}
bank1.deposit(dollars, cents);//should call upon the seprate deposit funtction below
}
else if (anwser == 2)
{
cout << "Enter in how much you want to withdraw in dollars:";
cin >> dollars;
cout << "Enter in how much you want to withdraw in cents:";
cin >> cents;
if (dollars < 0 || cents < 0)
{
cerr << "Invalid!" << endl;
exit(1);
}
bank1.withdraw(dollars, cents);
}
}
SavingsAccount::SavingsAccount(int d, int c)
{
dollars = d;
cents = c;
}
void SavingsAccount::convert(int d, int c)
{
dollars = dollars + c / 100;
cents = c % 100;//% used for the remainer
}
void SavingsAccount::deposit(int d, int c)
{
dollars += d;//d is where the program keeps track of the values
cents += c;
if (cents >= 100)
{
convert(d, c);
}
//total_money=???
total(dollars, cents);
}
void SavingsAccount::withdraw(int d, int c)
{
dollars += d;
cents += c;
if (cents >= 100)
{
convert(c, d);
}
//total_money=???
total(dollars, cents);
}
void SavingsAccount::total(int d, int c)
{
cout << "Total money: " <<d<<"."<< c<< endl;
}
The code seems to be a little messy and there are some wrong things happening here:
The method set() does nothing.
The field total_money is never initialized, set or queried.
The main() method somehow landed between the implementations of SavingsAccount, which is not a problem but makes your code harder to read.
convert is a non-static member function, so why don't you use the fields dollars and cents directly by first checking for a cent overflow and then modifying them in the overflow case.
In the method deposit(), the member variables are updated as expected. But then, convert() is called with the methods parameters and not with the fields. This will not change dollars or cents in any way (best to implement convert() as described in 4). At the end, you call total() again with the field values, which weren't converted.
The method withdraw() does exactly the same as deposit(). Did you mean to use -=?
total() does nothing else than printing the value. First, this could again be done using the fields instead of parameters (as it is not static), and second, you should rename this method to something like print() and parameterize it with an ostream.
Depending on how you would change your code, some methods may as well be private.
A well-formed program could look like this:
#include<iostream>
using namespace std;
class SavingsAccount {
unsigned int dollars;
unsigned int cents;
double total_money; //actually not necessary
static double getDoubleVal(unsigned int, unsigned int);
void convert();
public:
SavingsAccount();
SavingsAccount(unsigned int, unsigned int);
void setValues(unsigned int, unsigned int);
void deposit(unsigned int, unsigned int);
void withdraw(unsigned int, unsigned int);
ostream& print(ostream&) const;
}
double SavingsAccount::getDoubleVal(unsigned int d, unsigned int c) {
return d + (c / 100.0);
}
void SavingsAccount::convert() {
dollars += cents / 100 //integer divison on purpose
cents %= 100;
total_money = getDoubleVal(dollars, cents);
}
SavingsAccount::SavingsAccount() : dollars{ 0 }, cents{ 0 }, total_money{ 0.0 } {
}
SavingsAccount::SavingsAccount(unsigned int d, unsigned int c) : dollars{ d }, cents{ c }, total_money{ getDoubleVal(d, c) } {
convert();
}
void SavingsAccount::setValues(unsigned int d, unsigned int c) {
dollars = d;
cents = c;
convert();
}
void SavingsAccount::deposit(unsigned int d, unsigned int c) {
setValues(dollars + d, cents + c);
}
void SavingsAccount::withdraw(unsigned int d, unsigned int c) {
//You should also check for unsigned int underflow here
setValues(dollars - d, cents - c);
}
ostream& SavingsAccount::print(ostream& o) const {
o << total_money;
return o;
}
ostream& operator<<(ostream& o, const SavingsAccount& sa) {
return sa.print(o);
}
int main() {
SavingsAccount sa1 = SavingsAccount();
SavingsAccount sa2 = SavingsAccount(1337, 42);
cout << sa1 << sa2 << endl;
return 0;
}
Sorry for any mistakes in the code, especially formatting, I wrote this on my phone...
I have modified both the user defined classes to have constructors that accepts an object of the other class as it's argument.
Does this cover all the bases or do I have to overload the assignment operator and the type-cast operator as well to handle all the implicit and explicit type casting cases?
Eg:
#include <iostream>
using namespace std;
class Celsius; // Forward Declaration
class Fahrenheit {
double temp;
public:
Fahrenheit(double d = 0.0) : temp(d) {}
Fahrenheit(Celsius);
void setTemp(double d) { temp = d; }
double getTemp() { return temp; }
void print() { cout << "\nThe temperature value in Fahrenheit is " << temp << endl; }
};
class Celsius {
double temp;
public:
Celsius(double d = 0.0) : temp(d) {}
Celsius(Fahrenheit f) { temp = ((f.getTemp()-32) * 5) / 9; }
void setTemp(double d) { temp = d; }
double getTemp() { return temp; }
void print() { cout << "\nThe temperature value in Celsius is " << temp << endl; }
};
Fahrenheit::Fahrenheit(Celsius c) { temp = ((c.getTemp() * 9) / 5) + 32; }
int main() {
Fahrenheit t1(20);
Celsius t2(t1);
Fahrenheit t3(50);
t2.print();
t2 = (Celsius) t3;
t2.print();
cin.get();
return 0;
}
I have an array of objects which all derive from the class BaseStudent.
BaseStudent**studentlist = new BaseStudent*[atoi(listSize.c_str())];
That array is populated with either derived Math, English or History objects. I'm now trying to print out specific data from each object in the array and output it to a file.
for (int j=0; j<atoi(listSize.c_str()); j++){
if(studentlist[j]->getMT() == ENGLISH){
output << studentlist[j]->GetFN()<<" "<<studentlist[j]->GetLN();
output << right << setw(42) << studentlist[j]->GetFinal(); // this is an English public function but I can't call this.
}
}
I need to be able to access the derived classes private member data from the array of objects.
Here's my header. As you can see I have a setter and getter for every protected member data.
#include <iostream>
#include <string>
using namespace std;
#ifndef BASESTUDENT_H
#define BASESTUDENT_H
enum MajorType {ENGLISH, HISTORY, MATH};
// *********************************************************************
// Base class. All other classes (Enlish, History, Math) inherit from
// this class.
// *********************************************************************
class BaseStudent
{
public:
BaseStudent();
BaseStudent(string fn, string ln, string m);
string GetFN(){return firstName;}
string GetLN(){return lastName;}
MajorType getMT(){return course;}
void SetFN(string fn){firstName = fn;}
void SetLN(string ln){lastName = ln;}
void SetMT(string m);
protected:
string firstName;
string lastName;
MajorType course;
}; // End Base class
// *********************************************************************
// Enlish class.
// *********************************************************************
class English: public BaseStudent
{
public:
English(string fn, string ln, string m, double a, double p, double mt, double f);
double FinalAverage();
double GetAttendance(){return attendance;}
double GetProject(){return project;}
double GetMidterm(){return midterm;}
double GetFinal(){return final;}
double GetFinalAverage(){return finalAverage;}
void SetAttendance(double a){attendance = a;}
void SetProject(double p){project = p;}
void SetMidterm(double m){midterm = m;}
void SetFinal(double f){final = f;}
void SetFinalAverage(double fa){finalAverage = fa;}
protected:
double attendance;
double project;
double midterm;
double final;
double finalAverage;
}; // End English class
// *********************************************************************
// History class.
// *********************************************************************
class History: public BaseStudent
{
public:
History(string fn, string ln, string m, double t, double mt, double f);
double FinalAverage();
double GetTermPaper(){return termPaper;}
double GetMidterm(){return midterm;}
double GetFinalExam(){return finalExam;}
double GetFinalAverage(){return finalAverage;}
double FinalExam(){return finalExam;}
void SetTermPaper(double t){termPaper = t;}
void SetMidterm(double m){midterm = m;}
void SetFinalExam(double f){finalExam = f;}
void SetFinalAverage(double fa){finalAverage = fa;}
protected:
double termPaper;
double midterm;
double finalExam;
double finalAverage;
}; // End History class.
// *********************************************************************
// Math class.
// *********************************************************************
class Math: public BaseStudent
{
public:
Math(string fn, string ln, string m, double q1, double q2, double q3,
double q4, double q, double t1, double t2, double f);
double FinalAverage();
double GetQuiz1(){return quiz1;}
double GetQuiz2(){return quiz2;}
double GetQuiz3(){return quiz3;}
double GetQuiz4(){return quiz4;}
double GetQuiz5(){return quiz5;}
double GetFinalExam(){return finalExam;}
double GetTest1(){return test1;}
double GetTest2(){return test2;}
double GetQuizAverage(){return quizAverage;}
double GetFinalAverage(){return finalAverage;}
void SetQuiz1(double q){quiz1 = q;}
void SetQuiz2(double q){quiz2 = q;}
void SetQuiz3(double q){quiz3 = q;}
void SetQuiz4(double q){quiz4 = q;}
void SetQuiz5(double q){quiz5 = q;}
void SetTest1(double q){test1 = q;}
void SetTest2(double q){test2 = q;}
void SetFinalExam(double q){finalExam = q;}
void SetQuizAverage();
void SetFinalAverage(double fa){finalAverage = fa;}
protected:
double quiz1;
double quiz2;
double quiz3;
double quiz4;
double quiz5;
double test1;
double test2;
double finalExam;
double quizAverage;
double finalAverage;
}; // End Math class.
#endif
Do I need some sort of implementation of virtual functions?
Here's my driver so far:
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
#include"basestudent.h"
using namespace std;
int main(void)
{
string listSize;
string fileIn = "";
string fileOut = "";
string firstname ="";
string lastname ="";
string major = "";
string eolDummy;
int mQuiz1, mQuiz2, mQuiz3, mQuiz4, mQuiz5, mTest1, mTest2, mFinalExam;
int eAttendance, eProject, eMidterm, eFinalExam;
int hTermPaper, hMidterm, hFinalExam;
ifstream input;
ofstream output;
do{
input.clear();
cout << "Please enter the filename: ";
cin >> fileIn;
cout << "Please enter an output name: ";
cin >> fileOut;
input.open(fileIn);
if (!input)
cout << "Invalid file, please enter again." << endl;
} while(!input);
input >> listSize;
BaseStudent**studentlist = new BaseStudent*[atoi(listSize.c_str())];
int i = 0;
while (!input.eof())
{
getline(input, lastname, ',');
getline(input, firstname, '\n');
input >> major;
if (major == "Math") {
input >>mQuiz1>>mQuiz2>>mQuiz3>>mQuiz4>>mQuiz5>>mTest1>>mTest2
>>mFinalExam>>eolDummy;
// Math Constructor call
// Array += object
studentlist[i] = new Math(firstname,lastname,major,mQuiz1,mQuiz2,mQuiz3,mQuiz4,mQuiz5,
mTest1,mTest2,mFinalExam);
}
else if (major == "History"){
input >>hTermPaper>>hMidterm>>hFinalExam>>eolDummy;
// History Constructor call
// Array += object
studentlist[i] = new History(firstname,lastname,major,hTermPaper,hMidterm,hFinalExam);
}
else if(major == "English"){
input >>eAttendance>>eProject>>eMidterm>>eFinalExam>>eolDummy;
// English Constructor call
// Array += object
studentlist[i] = new English(firstname,lastname,major,eAttendance,eProject,eMidterm,eFinalExam);
}
i++;
}
output.open(fileOut);
output << "Student Grade Summary" << endl;
output << "---------------------" << endl << endl;
output << "ENGLISH CLASS "<<endl<<endl;
output << "Student Final Final Letter"<<endl;
output << "Name Exam Avg Grade"<<endl;
output << "----------------------------------------------------------------"<<endl;
for (int j=0; j<atoi(listSize.c_str()); j++){
if(studentlist[j]->getMT() == ENGLISH){
output << studentlist[j]->GetFN()<<" "<<studentlist[j]->GetLN();
output << right << setw(42) << studentlist[j]->
input.close();
output.close();
return 0;
}
When you take the pointer from your array, you need to cast it using dynamic_cast to the appropriate class
e.g.
BaseStudent *p = somearray[0];
if ( English* pEnglish = dynamic_cast<English*>(p) )
{
// call the methods
cout << p->FinalAverage();
...
}
else if ( History* pHistory = dynamic_cast<History*>(p) )
{
// call the methods
}
else if ( Math* pMath = dynamic_cast<Math*>(p) )
{
// call the methods
}
btw use a vector instead of a raw array, it is more convenient and safer.
std::vector<BaseStudent*> yourvector;