Ads

Ads

View Answers

March 23, 2009 at 2:16 AM

Hi friend,

Code to help in solving the problem :

import java.io.*;

class Square

{

public static void main(String[] args) throws IOException

{

boolean boolexit=true;

do

{

final double smallValue = 1.0E-14 ;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the float value ");

double val = Double.parseDouble(br.readLine());

System.out.println("Do you want the (s)quare or square (r)oot of" + val);

String type=br.readLine();

if(type.equals("R") || type.equals("r"))

{

double N = val ;

if(N>0)

{

double guess = 1.00 ;

while ( Math.abs( N/(guess*guess) - 1.0 ) > smallValue )

{

// calculate a new value for the guess

guess = N/(2*guess) + guess/2 ;

}

System.out.println("The square root of "+N+" is "+ guess);

}

else

{

System.out.println("You must have a positive number for square root.");

System.out.println("Do you want the (s)quare or square (r)oot of" + val);

type=br.readLine();

}

}

if(type.equals("S") || type.equals("s"))

{

double sqval=val*val;

System.out.println("The number "+ val+" squared has the value "+ sqval);

}

System.out.println("Do you want to enter more data? y/n: y ");

String exit= br.readLine();

if(exit.equals("N") || exit.equals("n"))

{

boolexit=false;

}

}

while (boolexit);

}

}

Thanks

Code to help in solving the problem :

import java.io.*;

class Square

{

public static void main(String[] args) throws IOException

{

boolean boolexit=true;

do

{

final double smallValue = 1.0E-14 ;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the float value ");

double val = Double.parseDouble(br.readLine());

System.out.println("Do you want the (s)quare or square (r)oot of" + val);

String type=br.readLine();

if(type.equals("R") || type.equals("r"))

{

double N = val ;

if(N>0)

{

double guess = 1.00 ;

while ( Math.abs( N/(guess*guess) - 1.0 ) > smallValue )

{

// calculate a new value for the guess

guess = N/(2*guess) + guess/2 ;

}

System.out.println("The square root of "+N+" is "+ guess);

}

else

{

System.out.println("You must have a positive number for square root.");

System.out.println("Do you want the (s)quare or square (r)oot of" + val);

type=br.readLine();

}

}

if(type.equals("S") || type.equals("s"))

{

double sqval=val*val;

System.out.println("The number "+ val+" squared has the value "+ sqval);

}

System.out.println("Do you want to enter more data? y/n: y ");

String exit= br.readLine();

if(exit.equals("N") || exit.equals("n"))

{

boolexit=false;

}

}

while (boolexit);

}

}

Thanks

Ads

Related Tutorials/Questions & Answers: