Problem:
Design and implement an algorithm to compute the reciprocal of a number.
Solution:
package com.myprograms;
import java.util.Scanner;
public class Reciprocal {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number: ");
String n = s.nextLine();
System.out.println("the reciprocal of " + n + " is " + findTheReciprocal(n));
s.close();
}
public static String findTheReciprocal(String n){
String result = "";
if(n.contains("/")){
String[] strings = n.split("/");
result = strings[1] + "/" + strings[0];
}
else{
result = "1" + "/" + n;
}
return result;
}
}
Output:
enter the number:
3/4
the reciprocal of 3/4 is 4/3
Design and implement an algorithm to compute the reciprocal of a number.
Solution:
package com.myprograms;
import java.util.Scanner;
public class Reciprocal {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number: ");
String n = s.nextLine();
System.out.println("the reciprocal of " + n + " is " + findTheReciprocal(n));
s.close();
}
public static String findTheReciprocal(String n){
String result = "";
if(n.contains("/")){
String[] strings = n.split("/");
result = strings[1] + "/" + strings[0];
}
else{
result = "1" + "/" + n;
}
return result;
}
}
Output:
enter the number:
3/4
the reciprocal of 3/4 is 4/3
enter the number:
8
the reciprocal of 8 is 1/8
No comments:
Post a Comment