Help with creating functions

After recently learning how to make a new function, I cannot get it to run properly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <math.h>

int thirdside(double a, double b);

int main()
{
	double y, z;
	printf("Please Enter in Two Values for The Sides of Your Right Triangle.\n");
	scanf("%f", &y);
	scanf("%f", &z);
	thirdside(y,z);	
}
int thirdside(double a, double b)
{
	double c;
	a = pow(a,2);
	b = pow(b,2);
	c = (a + b);
	c = sqrt(c);
	printf("The Hypotenuse of Your Triangle is: %f",c);
}
well you have it returning int when you return nothing (ie you want void). other than that looks good.
a function has a "type". This means it returns a value of that type. An int function returns an int, a char function returns a char, and so on.

Your int main function should return an int at the end.

Add this line...

return 0;

also change thirdside function to void. Void functions return nothing.
@manga: you dont need to do that. it implicitly returns 0 at the end
Cool, but wouldn't that still be considered bad form?
Now i have fixed the void rather than int problem, but it returns a "0" instead of the third side's value.
You have to decide if you want the value returned or not. In the code above at line 12 you don't use the return value, so why return anything?

The better style here would be for thirdside to return c; and to move the output statement to after line 12. Note by doing this you need to declare thirdside as type double (that's what c is) and then in main you need to store the returned value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <math.h>

double thirdside(double a, double b);

int main()
{   double y, z, c;
    printf("Please Enter in Two Values for The Sides of Your Right Triangle.\n");
   scanf("%lf", &y);
   scanf("%lf", &z);
    c = thirdside (y,z);	
    printf ("The Hypotenuse of Your Triangle is: %lf\n",c);
}
double thirdside(double a, double b)
{   double c;
    a = pow(a,2);
    b = pow(b,2);
    c = (a + b);
    c = sqrt(c);
    return c;
} 

Note: Your scanf and printf descriptors need to be %lf, not %f because you're using doubles not floats.

Manga wrote:
wouldn't that still be considered bad form?

Yes, to not explicitly return a value is considered poor form. While C++ does enforce that a 0 is returned, it is better to show that you explicity wanted to return a 0. While it might be redundant, it shows anyone looking at your code that you explicitly considered that case. In any case, the compiler will remove the redundant code.
Last edited on
Thank You,
My program now functions properly.
Topic archived. No new replies allowed.