Java-谈谈从一加到一百的那些事~~
程序员文章站
2022-05-05 17:38:44
...
单纯的从一加到一百,我用了while
package choer02;
public class jdkk {
public static void main(String[] args) {
int sum=0;
int i=0;
while(i<=99) {
i++;
sum+=i;
}
System.out.println("1+2+...+100="+sum);
}
}
一到一百以内的奇数相加
用while
package choer02;
public class jdkk {
public static void main(String[] args) {
int sum=0;
int i=0;
while(i<=99) {
i++;
sum+=i;
i++;
}
System.out.println("一到一百以内的奇数相加等于:"+sum);
}
}
试试do while
package choer02;
public class jnok {
public static void main(String[] args) {
int i=1;
int sum=0;
do {
sum+=i;
i++;
i++;
}while(i<=100);
System.out.println("一到一百以内的奇数相加为:"+sum);
}
}
再用个for
package choer02;
public class jnok {
public static void main(String[] args) {
int sum=0;
for(int i=1;i<=100;i++) {
sum+=i;
i++;
}System.out.println("一到一百以内的奇数相加为:"+sum);
}
}
while那里加个判断
package choer02;
public class jdkk {
public static void main(String[] args) {
int sum=0;
int i=0;
while(i<=99) {
i++;
if(i%2==1) {
sum+=i;
}else {
} i++;
}System.out.println("一到一百以内的奇数相加等于:"+sum);
}
}
偶数的话改改就好啦
。。。
推荐阅读