How to solve "undeclared identifier" and "redefinition of formal parameter"? - c++

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;
}

Related

Calling functions and passing arguments through map in c++?

I've been trying to figure out how I can use std::map to call functions and pass arguments to said functions based on a key.
I'm translating a project I made in Python to C++, but I've been stuck on this, and I really don't want to resort to a mess of if-elses.
The way I did that in Python was as so:
return_operation = {
"*": Operations.multiply,
"^": Operations.exponent,
"**": Operations.exponent
etc...
}
result = return_operation["*"](num_1, num_2)
Is there some sort of way to accomplish this is C++? I've tried using std::map but I keep getting:
Error C2276 '&': illegal operation on bound member function expression.
I'm still very new to C++ and I'm totally lost.
namespace std{
class Calculator {
public:
void multiply(double num_1, double num_2) {
cout << "MULTIPLYING!" << endl;
// Normally it would return the result of multiplying the two nums
// but it only outputs to the console until I can figure this out.
}
void initialize() {
void (Calculator::*funcPtr)();
funcPtr = &multiply;
unordered_map<string, Calculator()> operator_function = {
{"*", &multiply}
};
}
};
}
First off, you can't add custom types to the std namespace. Only specializations of existing templates.
Second, you are using the wrong mapped type for the unordered_map. Try something more like this instead:
class Calculator {
private:
typedef double (Calculator::*FuncType)(double, double);
unordered_map<string, FuncType> operator_function = {
{"*", &Calculator::multiply},
{"^", &Calculator::exponent},
{"**", &Calculator::exponent}
// and so on ...
};
double multiply(double num_1, double num_2) {
cout << "MULTIPLYING!" << endl;
return num_1 * num_2;
}
double exponent(double num_1, double num_2) {
cout << "EXPONENT!" << endl;
return pow(num_1, num_2);
}
public:
double do_math(string op, double num_1, double num_2) {
FuncType func = operator_function[op];
return (this->*func)(num_1, num_2);
}
};
Then, to call a function in the map, you can do this:
Calculator calc;
...
double result = calc.do_math("*", num_1, num_2);
Online Demo
Alternatively, Calculator doesn't really need to be stateful in this example, so the methods could be static to avoid needing an actual Calculator object:
class Calculator {
private:
typedef double (*FuncType)(double, double);
static unordered_map<string, FuncType> operator_function;
static double multiply(double num_1, double num_2) {
cout << "MULTIPLYING!" << endl;
return num_1 * num_2;
}
static double exponent(double num_1, double num_2) {
cout << "EXPONENT!" << endl;
return pow(num_1, num_2);
}
public:
static double do_math(string op, double num_1, double num_2) {
FuncType func = operator_function[op];
return func(num_1, num_2);
}
};
unordered_map<string, Calculator::FuncType> Calculator::operator_function = {
{"*", &Calculator::multiply},
{"^", &Calculator::exponent},
{"**", &Calculator::exponent}
// and so on ...
};
double result = Calculator::do_math("*", num_1, num_2);
Online Demo
Alternatively, you could use lambdas instead of class methods, eg:
class Calculator {
private:
using FuncType = std::function<double(double, double)>;
static unordered_map<string, FuncType> operator_function;
public:
static double do_math(string op, double num_1, double num_2) {
if (op == "**") op = "^";
FuncType func = operator_function[op];
return func(num_1, num_2);
}
};
unordered_map<string, Calculator::FuncType> Calculator::operator_function = {
{"*", [](double num_1, double num_2)
{
cout << "MULTIPLYING!" << endl;
return num_1 * num_2;
}
},
{"^", [](double num_1, double num_2)
{
cout << "EXPONENT!" << endl;
return pow(num_1, num_2);
}
}
// and so on ...
};
double result = Calculator::do_math("*", num_1, num_2);
Online Demo
If you're looking for a straight translation of your python code, then I'd go with something like this:
#include <cmath>
#include <functional>
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, std::function<double (double, double)>> return_operation{
{ "*", [](double a, double b) { return a * b; } },
{ "^", [](double a, double b) { return std::pow(a, b); } },
};
double r = return_operation["*"](5, 3); // r == 15
std::cout << r << std::endl;
return 0;
}
From a learning perspective, I totally recommend the answer by Remy Lebeau.

I was wondering why my calc() function didn't showed up in the output

// I am trying to calculate the initial cost, current cost, and profit in this program. But somehow the calc() function wasn't working.
#include<iostream>
using namespace std;
int main()
{
int shares;
cout<<"Enter the number of shares: ";
cin>>shares;
cout<<shares<<endl;
int buy;
cout<<"Enter the Price you bought in: $";
cin>>buy;
cout<<buy<<endl;
int current;
cout<<"Enter the current price: ";
cin>>current;
cout<<current<<endl;
void calc(float shares, float current, float buy, float &total, float &currentval, float &profit);
return 0;
}
void calc(float shares, float current, float buy, float &total, float &currentval, float &profit)
{
total=shares*buy;
currentval=shares*current;
profit=currentval-total;
cout<<"The total is $"<<total<<endl;
cout<<"The current value is $"<<currentval<<endl;
cout<<"The profit is $"<<profit<<endl;
}
The code you posted does not call the function calc. The line in the main that look like a call, is declaring a function, but it is never called.
void calc(float shares, float current, float buy, float &total, float &currentval, float &profit);
musst be replaced by:
float total,currentval,profit;
calc(shares, current, buy,total, currentval,profit);
Before calling function, you need declare it. For example
#include <iostream>
int calc(int arg1, int arg2); //this is declaring of function calc, which gas two int arguments and returns integer
int main()
{
//some your code
std::cout << calc(2, 3); //this prints 10
}
int calc(int arg1, int arg2) //here you define what does this function do
{
return arg1 * (arg1 + arg2); //something random calculating
};
You declare your calc function after main, but you need to do it before.

C++ functions with pointers

What is the error? How to solve it? This code is to find the area of the circle using pointers and functions. The error I am facing is that the &answer cannot be converted into float.
#include <iostream>
using namespace std;
void area(float, float);
int main()
{
float radius, answer = 0.0;
cout << "Enter a radius:"; // Take the radius from the user.
cin >> radius;
area(&radius, &answer);
cout << "Area of circle is:" << answer;
return 0;
}
void area(float *value, float *result) // This is the function to calculate the area.
{
*result = 3.142 * (*value) * (*value);
}
You can do one of the 2 things:
Change the prototype to void area(float*, float*);
Remove the prototype and move the function:
void area(float *value, float *result) // This is the function to calculate the area.
{
*result = 3.142 * (*value) * (*value);
}
above the main() function. Either of these will work.

Object Array of Derived Objects

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;

What's wrong with my temperature conversions?

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;
}