1.3任意の実数を出力する
4668 ワード
public class test {
public static void printDigit(int n){
System.out.print(n);
}
public static void printInt(int n){
if(n>=10){
printInt(n/10);
}
printDigit(n%10);
}
public static int getInt(double n){
return (int)n;
}
public static double getFraction(double n){
return (n-(int)n);
}
public static void printFraction(double fraction,int dec){
int i,tmp;
for(i=0;i<dec;i++){
fraction = fraction *10;
tmp = getInt(fraction);
printDigit(tmp);
fraction = getFraction(fraction);
}
}
public static double runUp(double n,int dec){
int i;
double tmp = 0.5;
for(i =0;i<dec;i++){
tmp = tmp / 10;
}
return (n + tmp);
}
public static void printReal(double n,int dec){
int tmp1;
double tmp2;
if(n<0)
n = -n;
n = runUp(n,dec);
tmp1 = getInt(n);
tmp2 = getFraction(n);
printInt(tmp1);
if(dec > 0){
System.out.print(".");
printFraction(tmp2,dec);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
printReal(4.65,2);
}
}
注意:runUp関数、そうでないと出力と必ずしも一致しません.