所以我之前提出了一个问题here,其中数组中的数字应该加在一起直到12的长度。
现在,我将如何添加其余数字,让我们说
double[] addMe = {147.04, 147.66, 148.27, 148.89, 149.51, 150.13, 150.76, 151.39, 152.02, 152.65, 153.29, 153.29,
10, 20 ,30,40,50,60,70,80,90,100,110,120, 10,20};
从上面我得到了答案
1804.9
780.0
1804.9
但它错过了最后两个数字10 and 20
,如果计数不等于12,我将如何添加它们?
感谢。
答案 0 :(得分:3)
修改这么多,你要添加所有数字,只是你不打印最后一笔,如果元素少于12
double sum=0.0;
for(int i=0;i<addMe.length;i++)
{
if(i%12==0 && i!=0)
{
System.out.println(sum);
sum=0;
}
sum +=addMe[i];
}
System.out.println(sum);//Just add this outside the loop
答案 1 :(得分:1)
试试这个:(如果你需要在循环中打印sum
,否则@ L-X的上述答案是更好的解决方案。)
double sum=0.0;
for(int i=0;i<addMe.length;i++)
{
if(i%12==0 && i!=0)
{
System.out.println(sum);
sum=0;
}
sum +=addMe[i];
if(i==addMe.length-1)
System.out.println(sum);
}
答案 2 :(得分:1)
你必须将它打印出循环,因为它在被平均除以12之前变为空,它不能成功打印,这就是你在循环之外添加print语句的原因,所以当它结束了,它将打印剩余的总和。
<slider.body>
<section class="cd-hero">
<ul id="SliderHome" class="cd-hero-slider autoplay">
<li class="selected">
<div class="cd-half-width cd-img-container">
<img src="http://codyhouse.co/demo/hero-slider/assets/tech-2.jpg" alt="tech 2">
</div>
<!-- .cd-half-width.cd-img-container -->
<div class="cd-half-width">
<div class="textcont-right">
<h2>Slide title here</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. In consequatur cumque natus!</p>
<a href="#0" class="cd-btn">Start</a>
</div>
</div>
<!-- .cd-half-width -->
</li>
<li style="background-image: url()">
<div class="cd-half-width cd-img-container">
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/Vhh_GeBPOhs?enablejsapi" frameborder="0" allowfullscreen></iframe>
</div>
<!-- .cd-half-width.cd-img-container -->
<div class="cd-half-width">
<div class="textcont-right">
<h2>text</h2>
<p> elit. In consequatur cumque natus!</p>
<a href="#" class="cd-btn">button</a>
</div>
</div>
<!-- .cd-half-width -->
</li>
</ul>
<div class="cd-slider-nav">
<nav>
<span class="cd-marker item-1"></span>
<ul>
<li class="selected"><a href="#0"></a></li>
<li><a href="#0"></a></li>
</ul>
</nav>
</div>
</section>
</body>
<强>输出强>
double[] addMe = {147.04, 147.66, 148.27, 148.89, 149.51, 150.13, 150.76, 151.39, 152.02, 152.65, 153.29, 153.29,
10, 20 ,30,40,50,60,70,80,90,100,110,120, 10,20};
double sum=0.0;
int y = 0;
for(int i=0;i<addMe.length;i++)
{
if(i%12==0 && i!=0)
{
y++;
System.out.print(y+": "+sum+"\n");
sum=0;
}else{
sum +=addMe[i];
}
}
y++;
System.out.println(y+": "+sum);
答案 3 :(得分:1)
class Sum {
public static void main(String[] arguments) {
double[] addMe = {
147.04, 147.66, 148.27, 148.89, 149.51, 150.13, 150.76, 151.39, 152.02, 152.65, 153.29, 153.29,
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 10, 20
};
double sum = 0.0;
double remainder = 0.0;
for (int i = 0; i < addMe.length; i++) {
if (i >= (addMe.length - addMe.length / 12)) {
remainder = remainder + addMe[i];
}
if (i % 12 == 0 && i != 0) {
System.out.println(sum);
sum = 0;
}
sum += addMe[i];
}
System.out.println("Remainder sum: " + remainder);
}
}