Trouble Calling A Validation Boolean Function

I am trying to write code that will validate whether a triangle is valid or not. I have to use three functions, two doubles and one bool. The problem is whenever I call the bool function isValidTriangle, I just get a random string of numbers such as "001616c7", which then messes up the calcArea function. Any help would be greatly appreciated! Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;

double getDouble(string prompt, double min, double max);
bool isValidTriangle(double s1, double s2, double s3);
double calcArea(double s1, double s2, double s3);

int main() {

    cout << "This program calculates the area of a triangle." << endl;
    double s1 = getDouble("Enter the length of side 1 (1-100): ",1,100);
    double s2 = getDouble("Enter the length of side 2 (1-100): ", 1, 100);
    double s3 = getDouble("Enter the length of side 3 (1-100): ", 1, 100);
    isValidTriangle(s1, s2, s3);

    calcArea(s1, s2, s3);
    if (calcArea < 0) cout << "Sorry, that is not a valid triangle.";
    else cout << "The area of the triangle is " << fixed << showpoint << setprecision(1) << calcArea;

    system("pause");
    return 0;
}


double getDouble(string prompt, double min, double max) {
    double guess;
    cout << prompt;
    cin >> guess;
    return guess;
}
bool isValidTriangle(double s1, double s2, double s3) {
    double largest = s1;
    if (s2 > largest) largest = s2;
    if (s3 > largest) largest = s3;
    
    if (largest * 2 < s1 + s2 + s3) {
        return true;
    }
    
    return false;
   
}

double calcArea(double s1, double s2, double s3) {
    
    if (isValidTriangle == false) return -1;
    double perimeter = s1 + s2 + s3;
    double s = perimeter / 2;
    double area = sqrt(s * ((s - s1)*(s - s2)*(s - s3)));
    return area;
}
Your isValidTriangle will return either 'true' or 'false'. You need to catch this return value and use it to determine whether to call calcArea() function or not. If isValidTriangle returns true, call calcArea, otherwise don't call it and just print "Invalid Triangle".

Remove line 49: calling isValidTriangle in the calcArea function is unnecessary.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
bool isValidTriangle(double s1, double s2, double s3) {

    if(s1 <= 0 || s2 <= 0 || s3 <= 0) return false ; // *** added

    const double largest = std::max( { s1, s2, s3 } ) ; // #include <algorithm>
    // or:
    // double largest = s1>s2 ? s1 : s2 ;
    // if (s3 > largest) largest = s3;

    return (largest*2) < (s1+s2+s3) ;
}
Thank you both for your help! I was able to use some of the things you suggested to fix the problem and my program is now working properly!
Topic archived. No new replies allowed.