对于两个数字之间的数字的循环和

时间:2017-03-21 22:04:56

标签: c for-loop

我需要创建一个程序,它得到的数字总和从100到500.

int sum = 0;
for (int i = 1; i <10; i++)
{
    sum = sum + i;
    printf("%d", sum);
}

它应该打印55(1到10之间的数字之和),但它打印出136101521283645。

在此之后,我需要一个能够得到100到500之间数字之和的程序。

6 个答案:

答案 0 :(得分:2)

这里你只是从1到9做i的总和,并且每次循环都打印出这个总和。

相反,你应该这样做:

int sum = 0;
for (int i = 1; i <= 10; i++)
{
    sum += i;
}
printf("%d", sum);

对于100到500,请执行以下操作:

int sum = 0;
for (int i = 100; i <= 500; i++)
{
    sum += i;
}
printf("%d", sum);

答案 1 :(得分:0)

int sum = 0; for (int i = 1; i <10; i++) { sum = sum + i; } printf("%d", sum); 置于循环之外

"use strict";
<!--# include file="/ssi/config.js" -->
window.mymodule = function(mymodule) {};

答案 2 :(得分:0)

您应该更改它以便打印最终总和!

int sum = 0;
for (int i = 1; i <10; i++)
{
    sum = sum + i;
}
 printf("%d", sum);

所以你的最终节目(总和从100到500)将是这样的:

int sum = 0;
for (int i = 100; i <500; i++)
{
    sum = sum + i;
}
 printf("%d", sum);

答案 3 :(得分:0)

您需要在循环之外移动print语句。每次循环运行时,它都会打印每个结果。

答案 4 :(得分:0)

一种简单的方法是: 这是它的程序:

public class unoQuini {
    private int sum = 0;
    private static int menor = 1;
    private static int mayor = 5;
    public int getSum() {
      return sum;
    }
    public void setSum(int sum) {
      this.sum = sum;
    }
    public int getMenor() {
      return menor;
    }
    public void setMenor(int menor) {
      this.menor = menor;
    }
    public int getMayor() {
      return mayor;
    }
    public void setMayor(int mayor) {
      this.mayor = mayor;
    }
    public static void main (String Args[]){
      unoQuini unqui = new unoQuini(); 
      int sum2 = 0;
      for (int i = menor; i<= mayor;i++ ){
        sum2 += i;
        unqui.setSum(sum2);
      }
      System.out.println("Suma = "+ unqui.getSum());
    }
}

重要的部分是:

public static void main (String Args[]){
          unoQuini unqui = new unoQuini(); 
          int sum2 = 0;
          for (int i = menor; i<= mayor;i++ ){
            sum2 += i;
            unqui.setSum(sum2);
          }
          System.out.println("Suma = "+ unqui.getSum());
        }

答案 5 :(得分:0)

总之,除了10(TO编号)之外,你还可以在for循环中打印数字

int SumOfNumbers(int from, int to)
{
    int sum;
    if(from > to)
    {
       sum = from;
       from = to;
       to = sum
    }
    sum = 0;
    for(int i = from; i <= to; ++i)
       sum += i;
    return sum;
}

然后你就可以调用ur func

sum = SumOfNumbers(from, to);
printf("%d\n");