Kamila Nowak
Kamila Nowak

Reputation: 59

Why there result is zero, not the right sqrt?

As in the title, when I want to know the result of 'liczba' and i choose 25, the result is 0.0000? The problem is in selected lines where i wrote comments . Thanks for help.

#include <stdio.h>
#include <math.h>
#define ACCURACY (1.e-5) 
double pierwiastek(double liczba);

int main( void ) {

  double liczba;

  for(;;){

    printf("\nPodaj wartosc liczby dodatniej (-1 konczy program):\n");
    scanf("%lf",&liczba);

    if(liczba<0.0) break;

    pierwiastek(liczba);
    printf("\nliczba %20.15lf, zalozona dokladnosc obliczania pierwiastka: %20.15lf\n", 
       liczba, ACCURACY);
    printf("\tpierwiastek liczby: obliczony %20.15lf, dokladny %20.15lf\n", 
       pierwiastek(liczba), sqrt(liczba));//<---- there
      printf("\nPierwiastek z pierwiastka: %lf",pierwiastek(pierwiastek(liczba)));//<-----there

  }
  return 0;
}

double pierwiastek(double liczba)
{
    double pierwiastek = 1.0f;
    double temp;
    //wzor Herona
    do{
      temp = pierwiastek;
      pierwiastek = 0.5f * (temp + liczba/temp);

    } while(fabs(pierwiastek*pierwiastek - liczba)/liczba > ACCURACY); 

}

Upvotes: 1

Views: 88

Answers (1)

gsamaras
gsamaras

Reputation: 73366

You don't return anything from your function. I think you meant to say:

double pierwiastek(double liczba)
{
  ..
  return pierwiastek;
}

A few notes in your code though:

This:

ierwiastek(liczba);

has no effect, since the function passes liczba by value, and you don't store the return of the function anywhere, which doesn't make sense. Usually, you would do:

double result = pierwiastek(liczba);

Here:

printf("\nPierwiastek z pierwiastka: %lf", pierwiastek(pierwiastek(liczba)));

I do not what you mean to say, but calling the function, and passing its result to another function call of the same function, seems a bit unusual. I would suggest you to double think about that line of code again.

Upvotes: 7

Related Questions