k.91221
k.91221

Reputation: 31

square root using Babylonian method returns wrong value?

For the function isqroot() to calculate the square root using Babylonian method with one degree of precision and return it in a struct.

I'm unable to return the value to the struct and when I compile it is returning garbage value.

Here is my code:

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

struct rootStruct {
    int rootInt;
    int rootFraction;
};

typedef struct rootStruct RootStruct;
RootStruct* isqroot (int n) {
    /*We are using n itself as initial approximation*/
    RootStruct* root=(RootStruct* )malloc(sizeof(RootStruct));
    float x = n;
    float y = 1;
    float e = 0.1; /* e decides the accuracy level*/

    while(x - y > e) {
        x = (x + y)/2;
        y = n/x;
    }
    root->rootInt = (int)x/2;
    root->rootFraction = (int)(x-root->rootInt)*100;
    return root;
}

int main(){
    RootStruct* roo+t=(RootStruct* )malloc(sizeof(RootStruct));
    printf("the sqrt is %d\n%d\n",root->rootInt,root->rootFraction);
    return 0;
}

What is wrong with this code?

Upvotes: 2

Views: 148

Answers (1)

IKavanagh
IKavanagh

Reputation: 6187

You never call isqroot()... so root->rootInt and root->rootFraction are never set.

You also have a typo in

RootStruct* roo+t=(RootStruct* )malloc(sizeof(RootStruct));

it should be

RootStruct* root=(RootStruct* )malloc(sizeof(RootStruct));

without the +. However, this is unnecessary as you allocate memory in isqroot() and should probably be replaced by

RootStruct* root = isqroot(9);

Then don't forget to free() the memory at the end of main().


Just to note, you also shouldn't case the result of malloc() in C.


You have also implemented the algorithm incorrectly, it should be

RootStruct* isqroot (int n) {
    RootStruct* root=(RootStruct* )malloc(sizeof(RootStruct));

    float y = 1;
    float e = 0.1; /* e decides the accuracy level*/

    while(fabs(n - y*y) > e) {
        y = (y + (n / y)) / 2;
    }

    root->rootInt = (int) y;
    root->rootFraction = (int) (y - root->rootInt) * 100;

    return root;
}

where the complete corrected program is then

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

struct rootStruct {
    int rootInt;
    int rootFraction;
};

typedef struct rootStruct RootStruct;

RootStruct* isqroot (int n) {
    RootStruct* root=(RootStruct* )malloc(sizeof(RootStruct));

    float y = 1;
    float e = 0.1; /* e decides the accuracy level*/

    while(fabs(n - y*y) > e) {
        y = (y + (n / y)) / 2;
    }

    root->rootInt = (int) y;
    root->rootFraction = (int) (y - root->rootInt) * 100;

    return root;
}

int main() {
    RootStruct* root = isqroot(9);
    printf("The sqrt is %d.%d\n", root->rootInt, root->rootFraction);
    return 0;
}

The Wikipedia article on Computing Square Roots has a very easy to understand section on the Babylonian method.

Upvotes: 2

Related Questions