数字的总和

数字的总和

有了 ++ 和 -- 的更多了解,下面看看另外一个使用循环的例子。

试试看:数字的总和。

这个程序比 * 号画方框要有用有趣得多。假定想知道某条街上所有门牌号的总和是多少,这需要读入最大的门牌号,再使用 for 循环汇总所有的整数,从 1 加到输入的那个数值为止。

比如假设我们输入 5,那么就计算 1 + 2 + 3 + 4 + 5。

#include <stdio.h>

int main(void)
{
  long sum = 0L;                      /* 存储总数      */
  int count = 0;                      /* 存储每一个要统计的数 */

  /* 初始化要增加到的数 */
  printf("\n输入要求和的整数个数: ");
  scanf(" %d", &count);

  /* 从1到count的整数求和 */
  for(int i = 1 ; i <= count ; i++)
  {
    sum += i;
  }

  printf("\n前%d个数字的总数是 %ld\n", count, sum);
  return 0;
}Code language: PHP (php)

下面是更简化的方式:

#include <stdio.h>

int main(void)
{
  long sum = 0L;                      /* Stores the sum of the integers      */
  int count = 0;                      /* The number of integers to be summed */

  /* Read the number of integers to be summed */
  printf("\n输入要求和的整数个数: ");
  scanf(" %d", &count);

  /* Sum integers from 1 to count */
  for (int i = 1 ; i <= count ; sum += i++ );

  printf("\n从1到count的整数求和 %ld\n", count, sum);
  return 0;
}Code language: PHP (php)

直接在 for 循环的括号里面完成累加的同时让 i 递增。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注