例外输出:1 / 4,1 / 2,3 / 4,1,5 / 4,3 / 2 但是我的输出是十进制形式的。请帮助仅打印小数形式。
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
答案 0 :(得分:1)
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
答案 1 :(得分:1)
取输入字符串的形式,以便将采取在输入所需的格式,并通过把它分解“/”即someString.spit(“/”)。 之后,使一个for循环,并需要两个号码,并在两个不同的变量存储。 然后采取分割两者,并通过它们之间在使用“/”进行打印。
答案 2 :(得分:-1)
编写了一种可以将双数转换为分数的方法。使用它进行转换并按如下所示打印,
public static void main(String[] args) {
// write your code here
LinkedHashMap<String,String>category1=new LinkedHashMap();
category1.put("action","die hard");
Scanner s=new Scanner(System.in);
String answer=s.nextLine();
if (category1.containsKey(answer))
System.out.println(category1.get("action"));
if (category1.containsValue(answer))
System.out.println(category1.keySet());