+ 1
How to create function
simple class function
2 Answers
+ 16
in cpp
first declare your function after all header files
second call the function in main
third define your function i.e.,code your function
#include<iostream>
// declaration of function
int sum(int, int);
//don't forgot to put semicolon after declaration
int main()
{
// calling of function
cout<<sum(3,5);
return 0;
}
// definition of function
int sum(int x, int y)
{
//don't put semicolon here i.e., after sum(--)
return(x+y);
}
+ 2
if you want use class try something like this:
#include <iostream>
#include <string>
class root{
public:
double a, b, c;
void GetRoots(){
std::cout « "enter a: ";
std::cin » a;
std::cout « "enter b: ";
std::cin » b;
std::cout « "enter c: ";
std::cin » c;
/* Perform calculation */
double d = sqrt( b * b - 4. * a * c );
if(d < 0) {
std::cout « "There is no real root" « std::endl;
}
else {
double x1 = ( -b + d ) / ( 2. * a );
double x2 = ( -b - d ) / ( 2. * a );
/* Display output */
std::cout « "\nx1 = " « x1 « std::endl;
std::cout « "x2 = " « x2 « std::endl;
}
}
};
int main(){
root eval;
eval.GetRoots();
return 0;
}