1

I just had a quick question in regards to do a power of 1/2 in C, I know about the pow function but I wish to do something else.

My goal is to make the following line into code where h is elevated to 0.5 R = -(g/2) + (h)½

I have tried r = (-(g/2) + (h*½));

but I doubt thats correct.

Maria
  • 41
  • 6

2 Answers2

1

Use sqrt() from <math.h>. The operation of H to the power of 0.5 is the same as taking a square root of H. Use the inbuilt sqrt function to get a performance advantage.

#include <stdio.h>
#include <math.h>

int main () {
   /*variable definitions*/
   r = (-(g/2) + sqrt(h));
   /*output*/
   return(0);
}
0

First of all, you need to know that if you try:

double x = 1/2;
printf("%f",x);

you will get a result of 0.0000

Now for your equation:

#include <stdio.h>
#include <math.h>

int main()
{
   double r,g,h;
   printf("Please enter g: \n");
   scanf("%lf", &g);
   printf("Please enter h: \n");
   scanf("%lf", &h);
   r = -1 * (g/2.0) + pow(h,0.5);
   printf("The result is %lf", r);
   return 0;
 }
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Your first point is valid — though an explanation of why (integer division) would be a good idea. Your main answer seems to fly against the question commenting _'I know about the `pow` function but I wish to do something else'._ – Jonathan Leffler Dec 25 '18 at 20:17