Not declared in Scope - c++

I have wrote a simple average calculation program trying to calculate a semester average. When I compile the code I get an error telling me my 'inputExam' function was not declared in this scope. I've researched the error message and I can't figure out what to do to fix it.
I also get this error for the other functions, but once I understand my error I think I can fix the others.
#include <iostream>
using namespace std;
int main()
{
double finalExam=0.0;
double midterm = 0.0;
double quizzes = 0.0;
double labs = 0.0;
double semGrade=0.0;
midterm=inputExam("Midterm");
finalExam=inputExam("Final");
quizzes=inputAndAvgQuizzes();
labs=inputAndAvgLabs();
semGrade=(midterm*.2)+(finalExam*.2)+(labs*.5)+(quizzes*.1);
cout<<"Your End of Semester Grade is: " semGrade;
return 0;
}
double inputExam(string examType)
{
double grade;
cout<< "Enter the " examType " Score: ";
cin>>grade;
return (grade);
}
double inputAndAvgLabs()
{
double num [4];
double sum;
double avg;
if (int a=0, a<3,a++)
{
cout<<"What is the grade?"<<endl;
cin>>num[a]>>endl;
}
if (int a=0, a<3, a++)
{
sum=sum+num[a];
}
avg=sum/4;
return avg;
}
double inputAndAvgQuizzes()
{
double num[3];
double sum;
double avg;
double lowest = num[0];
if (int a=0, a<2,a++)
{
cout<<"What is the grade?"<<endl;
cin>>num[a]>>endl;
}
if (lowest>num[1])
{
lowest=num[1];
}
if (lowest>num[2])
{
lowest=num[2];
}
sum=num[1]+num[2]+num[3]-lowest;
avg=sum/2;
return avg;
}

You need to let it be known that those functions exist so add prototypes for your functions above main or define your functions there. Like so:
...
double inputExam(string examType);
double inputAndAvgLabs();
double inputAndAvgQuizzes();
int main() { ... }
//definitions after main
..or copy paste all those definitions above the call to main like so:
...
// Function defs here
// Prototypes no longer needed
...
int main() {...}
// Defs no longer needed here
Alternatively you can put all the definitions in an external file and compile it into the project via a make file or better yet, and as you progress, create classes in header and implementation files and include them in your file the same way(sort of) that you do #include <iostream>.
Another small nugget of advice would be to avoid using namespace std;. If not only in theory it's bad practice and can lead to namespace clashing in larger projects. If you, like me, hate typing std::string ... then add using std::string; to your code for the same ease of use.

In C/C++ you need to declare the function before you use it. In this case, it simply means declaring function prototypes before your main function and then implementing them after the main function.
Example:
// declare a prototype
double Function(int variable);
int main()
{
Function(5);
return 0;
}
// Implement the function
double Function(int variable)
{
/* Do Something */
}
Alternatively, you could change your code to the form:
// Implement the function first
double Function(int variable)
{
/* Do Something */
}
int main()
{
Function("Testing");
return 0;
}

Related

Using member function to solve equation C++

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I get these two errors and can't seem to figure out how to get rid of them. Any suggestions are much appreciated, thank you.
23 8 [Error] prototype for 'double equip::calcmass(double)' does not match any in class 'equip'
13 10 [Error] candidate is: double equip::calcmass()
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstring>
using namespace std;
class equip
{
public:
double mass[999999999], velocity, height, time[999999999];
double calcmass();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(double time)
{
int i = 0;
for(i=0; i=999999999; i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
equip rocket;
ifstream infile;
string filename;
cout<<"Enter input file name for time (time): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<999999999; i++)
{
infile>>rocket.time[i];
}
for(i=0; i<999999999; i++)
{
cout<<rocket.mass[i];
}
return 0;
}
In your class definition you've declared
double calcmass()
In the definition of the member function it's
double calcmass(double time)
They do not match. One takes a double as argument and the other does not.
You were missing a bunch of headers, and in the function declaration was missing the parameter presents in the function definition:
#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
class equip
{
public:
...
double calcmass(double time); // here was missing the parameter
...
};
double equip::calcmass(double time)
{
...
}
Also you are doing time[i] on time which is a double, so you can't use operator[]... If you want to pass an array, you can use pointer to double:
class equip{
...
double calcmass(double* time)
}
double equip::calcmass(double* time)
{
...
}

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.

Getting wrong output. Garbage value

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.

Array Initialization problems: Unexpected behavior

The following program builds perfectly. However, during execution, no matter what value of degree I provide, the program takes only 2 array elements as input. I suppose there might be a problem with the redeclaration of the arrays f[] and fDash[]. In JAVA, arrays can be easily redeclared using the new keyword. Is that possible in c++ too? If not, what is the alternative?
P.S. I am using CodeBlocks 13.12 and compiler settings are standard.
#include <iostream>
#include <cmath>
using namespace std;
class Polynomial
{
public:
void input(void);
void expression(void);
void derivative(void);
double value(double var);
double der(double var);
private:
int f[];
int fDash[];
int degree;
};
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
f[degree+1];
fDash[degree];
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>f[i];
}
for(int i=0;i<degree;i++)
{
fDash[i]=f[i+1]*(i+1);
}
}
void Polynomial::expression()
{
cout<<f[0];
for(int i=1;i<=degree;i++)
{
cout<<" + "<<f[i]<<"*x^"<<i;
}
}
void Polynomial::derivative()
{
cout<<fDash[0];
for(int i=1;i<degree;i++)
{
cout<<" + "<<fDash[i]<<"*x^"<<i;
}
}
double Polynomial::value(double var)
{
double val=0.0;
for(int i=0;i<=degree;i++)
{
val+=f[i]*pow(var,i);
}
return val;
}
double Polynomial::der(double var)
{
double val=0.0;
for(int i=0;i<degree;i++)
{
val+=fDash[i]*pow(var,i);
}
return val;
}
int main()
{
double lb,ub,step,var,accum=0.0,rms;
int counter=0;
Polynomial p;
p.input();
cout<<"\n\n\nPolynomial is:\nf(x) = ";
p.expression();
cout<<"\n\n\nDerivative is:\nf'(x) = ";
p.derivative();
cout<<"\n\n\nEnter x0,x1,Step:\t";
cin>>lb;
cin>>ub;
cin>>step;
cout<<"\n\n\n====================================";
cout<<"\n\nx\t|\tf\t|\tf'\n\n\n";
var=lb;
while(var<=ub)
{
cout<<var<<"\t|\t"<<p.value(var)<<"\t|\t"<<p.der(var)<<"\n";
accum+=pow(p.value(var),2.0);
var+=step;
counter++;
}
cout<<"\n====================================";
accum/=counter;
rms=sqrt(accum);
cout<<"\nRMS energy of f(x) = "<<rms;
return 0;
}
This does not compile on clang, it fails with "error: field has incomplete type 'int []' int f[];" and likewise for fDash.
Let's see how you declared these fields:
int f[];
int fDash[];
In C++, you can declare arrays with statically defined sizes like so:
int f[5];
int fDash[6];
If you want dynamic arrays, which you need in this case, you'd have to declare
int* f;
int* fDash;
and allocate memory for them with
f = new int[5];
You also must release that memory somewhere like so
delete [] f;
But beware - managing your own memory like this is error prone and should be avoided. You should just use std::vector instead, which is the equivalent of java.util.ArrayList:
std::vector<int> f;
std::vector<int> fDash;
And modify your input function like so:
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
int input;
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>input;
f.push_back(input);
}
for(int i=0;i<degree;i++)
{
fDash.push_back(f[i+1]*(i+1));
}
}
You don't use arrays correctly. You need to allocate memory if you want to use array of variable length. How use arrays in c++ see this and this, or use std::vector

Parameter Passing Converting Floats error

I'm having an issue with passing parameters for this simple program. I am getting a "cannot convert 'float*' to 'float' argument '2' to 'void getData(std::string, float, float, float, float)'" error when trying to compile this program. Can anyone figure out what I'm doing wrong? I've been trying forever. Note: Please ignore deprecated stuff like system("PAUSE") and a few other things. This is simple the way my teacher has thought me to code and this is what he wants me using for this program. I am aware of getchar() and I use it for practice and final work. Plus this shouldn't affect the program as I have been using it without issues before on small programs for my C++ class.
Here's the code:
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
void getData(string,float,float,float,float);
void getCalc(int,float,float,float,float,float,float,float,float,float,float);
void getPrint(float,float,float);
int main()
{
int const acres=1000;
string crop;
float cpa[4];
float yield[4];
float per[4];
float increase[4];
float cost[4];
float grossmin[4];
float grossmax[4];
float netmin[4];
float netmax[4];
float netave[4];
getData(crop,cpa,yield,per,increase);
getCalc(acres,cpa,yield,per,increase,cost,grossmin,grossmax,netmin,netmax,netave);
getPrint(netmin,netmax,netave);
system("PAUSE");
return 0;
}
void getData(string fcrop,float fcpa[],float fyield[],float fper[],float fincrease[])
{
for (int i=0;i<4;i++)
{
cout<<"Enter the crop: ";
getline(cin,fcrop);
cout<<"Enter the cost per acre:$ ";
cin>>fcpa[i];
cout<<"Enter the yield: ";
cin>>fyield[i];
cout<<"Enter $/bishell: ";
cin>>fper[i];
cout<<"Enter the percentage increase: ";
cin>>fincrease[i];
cin.ignore(80,'\n');
}
}
void getCalc(int acres,float fcpa[],float fyield[],float fper[],float fincrease[],float fcost[],float fgrossmin[],float fgrossmax[],float fnetmin[],float fnetmax[],float fnetave[])
{
for (int i=0;i<4;i++)
{
int acres=1000;
fcost[i]=acres*fcpa[i];
fgrossmin[i]=acres*fyield[i]*fper[i];
fgrossmax[i]=fgrossmin[i]+(fgrossmin[i]*fincrease[i]/100);
fnetmin[i]=fgrossmin[i]-fcost[i];
fnetmax[i]=fgrossmax[i]-fcost[i];
fnetave[i]=(fnetmin[i]+fnetmax[i])/2;
}
}
void getPrint(float fnetmin[],float fnetmax[],float fnetave[])
{
for (int i=0;i<4;i++)
{
cout<<"The minumum profit is:$ "<<fnetmin[i]<<endl;
cout<<"The maximum profit is:$ "<<fnetmax[i]<<endl;
cout<<"The average profit is:$ "<<fnetave[i]<<endl;
}
}
In the prototype you have written at the start of the program, this is written.
void getData(string,float,float,float,float) ;
It should be this instead identical to the one in its definition.
void getData(string,float[],float[],float[],float[]);
The function prototype should be same in its declaration and implementation.