int a = 1;
double b = 1.0;
double l = 10;
for (int i=1;i<=3;i++){
a=(int) b;
System.out.println("");
for (a=a;a<=l;a++){
System.out.print(a+" ");
}
l=l*2;
System.out.println("");
for ( b=a;b<=l;b++){
System.out.print(b+" ");
a=(int) b;
不起作用,请帮助。 输出应显示:
1 2 3 4 5 6 7 8 9 10 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 20.0 21 22 23 24 25 26 27 ...
每次从整数到双倍交替,直到达到100。
答案 0 :(得分:1)
尝试一下:
for(int i = 0 ; i < 100 ; i+=10){
for(int j = 1 ; j <= 10 ; j++){
if((i/10)%2 != 0){
double d = i+j;
System.out.print(d+" ");
}else{
System.out.print((i+j)+" ");
}
}
}
您也可以这样做,而不是将其转换为双精度,
if((i/10)%2 != 0){
System.out.print((i+j)+".0 ");
}
答案 1 :(得分:0)
从给定代码的外观看,您似乎忘记在末尾添加2个右括号。这是当我添加方括号并将其放在主函数中时的代码:
public static void main (String[] args)
{
int a = 1;
double b = 1.0;
double l = 10;
for (int i=1;i<=3;i++){
a=(int) b;
System.out.println("");
for (a=a;a<=l;a++){
System.out.print(a+" ");
}
l=l*2;
System.out.println("");
for ( b=a;b<=l;b++){
System.out.print(b+" ");
a=(int) b;
}
}
}
}
这是程序的输出:
1 2 3 4 5 6 7 8 9 10
11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 20.0
21.0 22.0 23.0 24.0 25.0 26.0 27.0 28.0 29.0 30.0 31.0 32.0 33.0 34.0 35.0 36.0 37.0 38.0 39.0 40.0
41.0 42.0 43.0 44.0 45.0 46.0 47.0 48.0 49.0 50.0 51.0 52.0 53.0 54.0 55.0 56.0 57.0 58.0 59.0 60.0 61.0 62.0 63.0 64.0 65.0 66.0 67.0 68.0 69.0 70.0 71.0 72.0 73.0 74.0 75.0 76.0 77.0 78.0 79.0 80.0
尽管输出不是您想要的,但它表明从double到int的转换有效。问题可能是语法错误。如果您仅对输出感兴趣,我可以提供一种替代方法:
public static void main (String[] args) throws java.lang.Exception
{
for (int i = 1; i < 100; ++i) {
if (((i-1) / 10) % 2 == 0) {
System.out.print(i);
} else {
System.out.print(Integer.toString(i) + ".0");
}
System.out.print(" ");
}
System.out.print(100.0);
}