我的代码打印两个限制之间的每个数字并求和.
如何每10个数字打印一行?
for (int i = nedreGrense; i <= øvreGrense; i++) {
sum = sum + i;
}
for (int tallStreng = nedreGrense; tallStreng < øvreGrense; tallStreng++){
System.out.print(tallStreng+"+");
}
System.out.print(øvreGrense+"="+sum);
解决方法:
由于您的限制可以是任何整数,因此如果nedreGrense可以是任何整数,
然后在nedreGrense增加10之后,它的值将不会改变,只有十分之一会改变,以检查我们是否必须使用%运算符来给出数字.
因此使用条件if((tallStreng!= nedreGrense)&&((tallStreng-nedreGrense)?== 0))
for (int i = nedreGrense; i <= øvreGrense; i++)
sum = sum + i;
for (int tallStreng = nedreGrense; tallStreng < øvreGrense; tallStreng++){
if( (tallStreng != nedreGrense) && ((tallStreng - nedreGrense)%10 == 0))
System.out.println();
System.out.print(tallStreng+"+");
}
System.out.print(øvreGrense+"="+sum);