I am new to C++, and for a beginner project I figured I could write a program that does the Pythagorean Theorem. It's work's like a charm ( i think haha) also it's accurate enough, but I wanted to know if I wrote more than i had to. I was wondering what I could do to shorten it and make it more efficient or did I miraculously write my first program pretty good? haha anywho here's the Code:
At line 31, c may be negative. I think you should test that before the sqrt().
Perhaps a, b and c should be of type double too, I don't see why not.
Not sure about line 66, just as the program ends, setting the title?
On the plus side, I don't think this is overly long, almost all the code serves a purpose. It's also good to see the use of functions to break the code into manageable chunks. The original question asked about making the code shorter or more efficient, well mostly any changes would be more a matter of style or preference rather than a real improvement, at least in my opinion.
Why change to double? Well, let's say the user is entering sides A and B. A = 3
B = 5
Answer = 5.83095
So far so good.
But what if the user wants to enter C = 5.83095 ?
Currently they are not able to do so.
How can c be negative? I suppose you could politely ask the users to enter sensible data. But it would be good practice to validate the input to confirm that is the case, and maybe output a message if the values cannot make a triangle.
Broadly speaking, users will sooner or later accidentally or deliberately enter invalid data, maybe through a simple typing error, or lack of concentration. The program should be able to handle that.
Still, perhaps that's a larger topic, including for example handling non-numeric data as well. At this stage you can regard it as something to be aware of for the future.
cout << "\nPlease enter a valid number";
cout << "\n\nEnter C: ";
cin >> b;
cout << "\nEnter A or B: ";
cin >> a;
while (b <= a);
so now if the user enters a number for C but then enters a larger number for A or B it will ask for another entry until its right.
One thing i would like to do is have the same statement pop up if the user inputs any character thats not a number example:
Enter C: 3
Enter A or B: TheFlyingByrd
Please enter a valid number.
But I have no clue how to make it recognize if its a number or not also I would like it to know if its a positive number or not. i was thinking you would have to add something like this:
while (b <= a || // something here that tells whether its a number or not || // and here for a positive number or not)
Wow JLBorges thank you so much for this. It would have taken me forever to figure that out haha but i am for all just starting to learn C++. I will study this code and learn from it for future reference. Again thank you.