C语言 两个数之间的循环求和

yzckvree  于 2023-06-05  发布在  其他
关注(0)|答案(7)|浏览(200)

我需要创建一个程序来计算从100到500的数字之和。

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

它应该打印55(1到10之间的数字之和),但它打印出136101521283645。
在此之后,我需要一个程序,得到从100到500的数字之和。

cedebl8k

cedebl8k1#

在这里,你只需要对i从1到9求和,然后在每个循环中输出这个和。
相反,你应该这样做:

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);
lsmepo6l

lsmepo6l2#

printf置于循环之外

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

mm9b1k5b3#

你应该改变它,这样它就可以打印出最终的总和!

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);
wydwbb8l

wydwbb8l4#

你需要将print语句移出循环。它在每次循环运行时打印每个结果。

smtd7mpg

smtd7mpg5#

一个简单的方法是:在这里它的程序:

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());
        }
ltskdhd1

ltskdhd16#

首先,你不包括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;
}

然后你就可以调用你的函数

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

brjng4g37#

// Print the sum of First n Natural Number

包含<stdio.h>

public void run(){

int n;
printf("Enter The Natural Number : ");
scanf("%d \n", n);

int sum = 0;
for (size_t i = 0; i <= n; i++)
{
    sum += i;
}

printf("Sum is : %d \n", sum);

return 0;

}

相关问题