Testing Absolute Values – C

#include <stdio.h>
#include <stdlib.h>

int gcd(int u, int v);
float absoluteValue (float x);


int main()
{
int result = 0;

float f1 = -15.0, f2 = 20.0, f3 = -5.0;
int i1 = -7.61;
float absoluteValueResult = 0.0;
float squareroot(float x);
result = gcd (150, 35);
printf("The gcd of 150 and 35 is %dn", result);

result = gcd(1023, 405);
printf("The gcd of 1023 and 405 is %dn", result);

printf("The gcd of 240 and 83 is %dnnn", gcd(83,240));

/* testing the absolute Value Fucntion */
absoluteValueResult = absoluteValue (f1);
printf("result = %.2fn",absoluteValueResult );
printf("f1 = %.2fn", f1);

absoluteValueResult = absoluteValue (f2) + absoluteValue (f3);
printf("result = %.2fn", absoluteValueResult);

absoluteValueResult = absoluteValue((float) i1);
printf("result = %.2fn", absoluteValueResult);

printf("%.2fn", absoluteValue (-6.0) / 4 );

printf("%.2fn", squareroot(-3.0));
printf("%.2fn", squareroot(16.0));
printf("%.2fn", squareroot(25.0));
printf("%.2fn", squareroot(9.0));
printf("%.2fn", squareroot(165.0));


return 0;
}

int gcd(int u, int v)
{
int temp;
while(v != 0)
{
temp = v % u;
u = v;
v = temp;
return u;
}
}


float squareroot(float x)
{
const float epsilon = .00001;
float guess = 1.0;
float returnValue = 0.0;

if(x < 0)
{
printf("Negative arguments to squareroot.n");
returnValue = -1.0;

}
else 
{
while (absoluteValue (guess * guess - x) >= epsilon)
guess = (x / (guess + guess) / 2.0 );

returnValue = guess;
}
return returnValue;
}
float absoluteValue(float x)
{
if (x < 0)
x = -x;
return x;
}

Scroll to top