例如, S(7,4)= 0.7+0.77+0.777+0.7777
输入整数d(1-9),n(10-3000),计算并输出S(d,n)
方法一:枚举算法
t = t / 10 + d / 10;
public class Page {
public static void main(String[] args){
int d, n; //记录输入的数
double s = 0;
double t = 0;
Scanner in = new Scanner(System.in);
System.out.println("请输入整数d, n:");
d = in.nextInt();
n = in.nextInt();
for(int i = 0; i < n; i++) {
t = t / 10 + (double)d / 10;
s += t;
}
System.out.print("S(d,n) = ");
System.out.println(String.format("%.8f", s)); //保留小数
}
}
方法二:省略循环求和
设S(9,n)= 0.9+0.99+…+0.999…99 = n - 0.111111…
则S(d,n)= S(9,n)* d / 9
public class Page {
public static void main(String[] args){
int d, n; //记录输入的数
double s = 0;
double t = 0;
Scanner in = new Scanner(System.in);
System.out.println("请输入整数d, n:");
d = in.nextInt();
n = in.nextInt();
s = (n-0.11111111) * d / 9;
System.out.print("S(d,n) = ");
System.out.println(String.format("%.8f", s)); //保留小数
}
}
d / 9十分妙!!!!!