Here is my program that calculated the Pythagorean equation using a user defined function called (pythagfun). All calculations I want to be done inside the function. The way main is in the code I would like to stay but with those specifications "biggest" is not calculating. I know "biggest" needs to be modified in order to make it not true to (biggest = -1). But I dont want to modify it in main, only in the pythagfun function. Any tips would be great.
#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
void pythagfun()
{
double a, b, c;
cout << "Please enter the length of side a: ";
cin >> a;
cout << "Please enter the length of side b: ";
cin >> b;
c = (sqrt(pow(a, 2.0) + (pow(b, 2.0))));
cout << "Side c is ";
cout << c << endl;
// if biggest is modified here it still is only true to the function not in main, correct?
}
int main()
{
string answer = "Yes";
double biggest = -1;
while (answer == "Yes")
{
pythagfun(); // only "main" line im allowed to modify
cout << "Do you want to continue (\"Yes\" or \"No\")?";
cin.ignore();
getline(cin, answer); //Program works up until this point
}
if (biggest > -1) // this part does not calculate
{
cout << "The largest answer for side c was " << biggest << endl;
}
}
Biggest is a local variable, so it is only local to functions.
You can change this by making it a global variable, by defining it outside of the functions. You are advised to avoid global variables if possible.
You could pass the value of biggest to pythagfun by using a pointer or reference argument.
i.e
1 2 3 4 5 6 7 8 9 10 11 12
void pythagfun(double *biggest)
{
double a, b, c;
cout << "Please enter the length of side a: ";
cin >> a;
cout << "Please enter the length of side b: ";
cin >> b;
c = (sqrt(pow(a, 2.0) + (pow(b, 2.0))));
cout << "Side c is ";
cout << c << endl;
//compare c to biggest and update biggest accordingly
}
I CHANGED YOUR PROGRAM A LITTLE BIT AND IT CHANGES THE VALUE OF BIGGEST TO THAT OF C, It does this by pass by reference.
Search for -nosa odiase c++ tutorial on you tube. I am gonna do all these stuffs
[code]#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
void pythagfun(double &x)
{
double a, b, c;
cout << "Please enter the length of side a: ";
cin >> a;
cout << "Please enter the length of side b: ";
cin >> b;
c = (sqrt(pow(a, 2.0) + (pow(b, 2.0))));
cout << "Side c is ";
cout << c << endl;
x=c;// i added this line
// if biggest is modified here it still is only true to the function not in main, correct?
}
int main()
{
string answer = "Yes";
double biggest = -1;
while (answer == "Yes")
{
pythagfun(biggest); // only "main" line im allowed to modify
cout << "Do you want to continue (\"Yes\" or \"No\")?";
cin.ignore();
getline(cin, answer); //Program works up until this point
}
if (biggest > -1) // this part does not calculate
{
cout << "The largest answer for side c was " << biggest << endl;
}
system("pause");
}