-
Right Triangle Program
Hello again!
I am having some trouble on this right triangle program I have to write for class. I have it written out, and it compiled/runs just fine. The problem is that it says everything is a right triangle! lol. Not completely sure why, but I know not everything I type in there could possibly be a right triangle. I was wondering if somebody might take a look at what I've got for me to try and figure out what's wrong? :)
Code:
# include <stdio.h>
# include <math.h>
int main()
{
double a;
double b;
double c;
double hypotenuse;
/*get lengths from user*/
printf("Insert the length of the hypotenuse, followed by the two\n");
printf("other sides of the triangle.\n");
scanf("%lf%lf%lf", &c, &a, &b);
c = sqrt((a * a)+(b * b));
if ((c = sqrt((a * a)+(b * b))))
{
printf("This is a right triangle");
}
else
{
printf("This is not a right triangle");
}
return 0;
}
Sorry in advance if I did something stupid. :confused: I'm still really new to this! Thank you for any help! :D
-
You are asking your user to input the legth of the hypotenuse in c...
Then on the very next line you assign c from a math result.
Right after that, you recalculate it *again* in your if statement.
Also the hypoteneuse variable is never used.
I'm thinking you need to rethink this just a tad... :D
-
Oops! Well, if it means anything I meant to remove the first stated Pythagorean theorem after I put it in the if statement. I just forgot to remove it. But yeah, I did define it twice differently with the scanf and if statement. Ok, let me go back into it and see what the heck I did. I'm too tired for this, lol.
Thank you! :) I'll post again once I work with it a little more.
-
I got it! :D It's all coming out right, but hopefully the code makes sense.
Code:
# include <stdio.h>
# include <math.h>
int main()
{
double a;
double b;
double c;
double sum;
printf("Insert the length of the hypotenuse, followed by the two\n");
printf("other sides of the triangle.\n");
scanf("%lf%lf%lf", &c, &a, &b);
sum = sqrt((a * a) + (b * b));
if (c == sum)
{
printf("This is a right triangle");
}
else
{
printf("This is not a right triangle");
}
return 0;
}
-
You really shouldn't check for exact equality when working with floating point numbers. Read this.
-
Gardhr is right about equality checks with floating point numbers... they are at best an approximation. There's this little troublemaker called "last bit ambiguity" where not all numbers can be accurately represented in floating point formats.
Try this...
Code:
if ( abs(c - sum) < .005) // adjust the .005 for your allowable margin of error
Printf(...