I'm currently writing a code that returns the area and perimeter of a triangle. It gets user inputted side lengths and calculates from there. When I try to compile it I get a message that the variables in the main function need to be initialized. I didn't think I needed to do this if the variables are chosen by the user. I'm very new to programming so I apologize if I am missing something obvious.
#include<iostream>
#include<cmath>
using namespace std;
cout << "The area of the triangle formed by the sides " <<
one << ", " << two << " and " << three << " is: " << sqrt(result) << endl;
cout << "The perimeter is: " << one + two + three << "\n\n";
system("pause");
return 0;
}
void title(){
cout << "Triangle Area Solution\n";
cout << "Welcome to Triangle City!\n\n\n";
}
void side1(double &first){
cout << "Type the size of side a: ";
cin >> first; cin.ignore(80, '\n');
while (first <= 0){
cout << "Please enter a valid side. Try again: ";
cin >> first; cin.ignore(80, '\n');
}
}
void side2(double &second){
cout << "Type the size of side b: ";
cin >> second; cin.ignore(80, '\n');
while (second <= 0){
cout << "Please enter a valid side. Try again: ";
cin >> second; cin.ignore(80, '\n');
}
}
void side3(double &third){
cout << "Type the size of side c: ";
cin >> third; cin.ignore(80, '\n');
while (third <= 0){
cout << "Please enter a valid side. Try again: ";
cin >> third; cin.ignore(80, '\n');
}
}
void area(double &answer){
double one, two, three, semi;
semi = (one + two + three)/2;
answer = (semi * (semi - one) * (semi - two) * (semi - three));
}
These are not the same as the ones in main, but instead are used only in this function. You will need to pass them in as a parameter in order to use them here.
It also seems you are using double result without initializing it when you try to take its root:
I think I'm getting confused with variable names now. I would want 'double one, two, three' to be the user inputs from the other three functions. If I were to initialize them wouldn't I essentially be choosing arbitrary values? Thanks.
You're right in that you wouldn't want to initialize them with just anything. What you need to do is pass them as parameters into your function. There are a couple ways to do this but the simplest will probably be to set up your function like this: